Thread: Some Switch not working in do-while loop

  1. #1
    Registered User
    Join Date
    May 2019
    Posts
    47

    Exclamation Some Switch not working in do-while loop

    Hello friends,
    I am newto C and was following tutorial on student record system where you insert,view,search,update,sort and delete functions

    i have no problems with the functions when i run it individully within the main however when i run those function within a switch statement which is within a do while loop..display and sort function not working


    here is my code
    i am posting the code for display and sort function only as they are not working within the do while loop

    Code:
    //    FUNCTION TO DISPLAY RECORDS
    
    
    void display()
    {
     FILE *fp1;
     fp1 = fopen("Record.dat", "r");
     printf("\nRoll Number\tName\tMark\n\n");
     while (fread(&stud, sizeof(stud), 1, fp1))
     printf("  %d\t\t%s\t%.2f\n", stud.rollno, stud.name, stud.mark);
     fclose(fp1);
    }
    
    /* FUNCTION TO SORT THE RECORD */
    void sort()
    {
        int a[20];
        int count = 0;
        int i,j,t,c;
        FILE *fpo;
        fpo = fopen("Record.dat","r");
        while(fread(&stud,sizeof(stud),1,fpo))
        {
            a[count]=stud.rollno;
            count++;
        }
       c = count;
       for(i=0;i<count-1;i++)
       {
           for(j=i+1;j<count;j++)
           {
               if(a[i]>a[j])
               {
                   t=a[i];
                   a[i]=a[j];
                   a[j]=t;
               }
           }
       }
       printf("Roll no.\tName\tMark\n\n");
       count =c;
       for(i=0;i<count;i++)
       {
           rewind(fpo);
            while(fread(&stud,sizeof(stud),1,fpo))
        {
            if(a[i]==stud.rollno)
            {
                printf("\n%d\t\t%s\t\t%2f",stud.rollno,stud.name,stud.mark);
            }
        }
    
    
       }
    }
    main function

    Code:
    int main()
    {
      //insert();
      //display();
      //search();
     //deletefile();
      //update();
      //sort();
    
    
      int c,emp;
      do
      {
          printf("\n\t----Select your Choice----------------\n");
          printf("\n\t1.INSERT\n\t2.DISPLAY\n\t3.SEARCH");
          printf("\n\t4.DELETE\n\t5.UPDATE\n\t6.SORT");
          printf("\n\t7.EXIT");
          printf("\n\n--------------------------------------\n");
          printf("\nEnter Your Choice:");
          scanf("%d",&c);
          printf("\n");
          switch(c)
          {
          case 1:
            insert();
            break;
          case 2:
            emp=empty();
            if(emp==0)
            {
               printf("\nTHE FILE IS EMPTY\n");
            }
            else
            {
                display();
                break;
            }
          case 3:
            search();
            break;
          case 4:
            deletefile();
            break;
          case 5:
            update();
            break;
          case 6:
            emp=empty();
            if(emp==0)
            {
               printf("\nTHE FILE IS EMPTY\n");
            }
            else
            {
                sort();
                break;
            }
          case 7:
            exit(1);
            break;
          default:
             printf("\nYour Choice is wrong\nPlease Try Again\n");
            break;
          }
    
    
    
    
      }while(c!=7);
      
        return 0;
    }
    thanks..any help will be highly appreciated
    Last edited by sash_007; 12-14-2019 at 04:51 PM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Your sort function is missing an fclose

    I wonder if any of the other code you've not posted has missing fclose calls as well.

    Especially one which might have left the file open for writing, which would prevent any of the code you posted from running.

    Now it a good time to learn how to use the debugger, so you can start answering your own "why isn't it working" questions.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    In addition to Salem's observations, I'm wondering if you're using global variables and, if so, why?

    What are lines 27 and 41 (of the first snippet) supposed to do?

    Line 69 of the second snippet (main) seems pretty useless because you exit the program on line 59 (which probably should be exit(0); btw because no error has occurred -- better still exit(EXIT_SUCCESS); but I don't think it should be exiting with 1. Even better than that, just get rid of that exit because it doesn't make a lot of sense)

    Check carefully where your breaks are in the switch. Are things dropping through to the next case in any circumstances/conditions?
    Last edited by Hodor; 12-15-2019 at 12:18 AM.

  4. #4
    Registered User
    Join Date
    May 2019
    Posts
    47
    Hello if the debugger shows no errors how can i debug?

    when i run the functions individually they run fine

    here is my full code for better understanding

    Code:
    #include<stdio.h>
    
    struct student
    {
     int rollno;
     char name[30];
     float mark;
    }stud;
    //    FUNCTION TO INSERT RECORDS TO THE FILE
    void insert()
    {
     FILE *fp;
     fp = fopen("Record.dat", "a");
     printf("Enter the Roll no   :");
     scanf("%d", &stud.rollno);
     printf("Enter the Name      :");
     scanf("%s", &stud.name);
     printf("Enter the mark      :");
     scanf("%f", &stud.mark);
     fwrite(&stud, sizeof(stud), 1, fp);
     printf("\nRECORD ADDED");
     fclose(fp);
    }
    //    FUNCTION TO DISPLAY RECORDS
    void display()
    {
     FILE *fp1;
     fp1 = fopen("Record.dat", "r");
     printf("\nRoll Number\tName\tMark\n\n");
     while (fread(&stud, sizeof(stud), 1, fp1))
     printf("  %d\t\t%s\t%.2f\n", stud.rollno, stud.name, stud.mark);
     fclose(fp1);
    }
    //    FUNCTION TO SEARCH THE GIVEN RECORD
    void search()
    {
     FILE *fp2;
     int r, s, avl;
     printf("\nEnter the Roll no you want to search  :");
     scanf("%d", &r);
     avl = avlrollno(r);
     if (avl == 0)
      printf("Roll No %d is not available in the file\n",r);
     else
     {
      fp2 = fopen("Record.dat", "r");
      while (fread(&stud, sizeof(stud), 1, fp2))
      {
       s = stud.rollno;
       if (s == r)
       {
        printf("\nRoll no = %d", stud.rollno);
        printf("\nName    = %s", stud.name);
        printf("\nMark    = %.2f\n", stud.mark);
       }
      }
      fclose(fp2);
     }
    }
    
    
    //    FUNCTION TO DELETE A RECORD
    
    
    
    
    void deletefile()
    {
     FILE *fpo;
     FILE *fpt;
     int r, s;
     printf("Enter the Roll no you want to delete :");
     scanf("%d", &r);
     if (avlrollno(r) == 0)
     {
         printf("Roll no %d is not available in the file\n", r);
     }
    
    
     else
     {
      fpo = fopen("Record.dat", "r");
      fpt = fopen("TempFile.dat", "w");
      while (fread(&stud, sizeof(stud), 1, fpo))
      {
       s = stud.rollno;
       if (s != r)
        fwrite(&stud, sizeof(stud), 1, fpt);
      }
      fclose(fpo);
      fclose(fpt);
      fpo = fopen("Record.dat", "w");
      fpt = fopen("TempFile.dat", "r");
      while (fread(&stud, sizeof(stud), 1, fpt))
       {
        fwrite(&stud, sizeof(stud), 1, fpo);
        printf("\nRECORD DELETED\n");
       }
      fclose(fpt);
      fclose(fpo);
     }
    
    
    
    
    }
    //    FUNCTION TO UPDATE THE RECORD
    void update()
    {
     int avl;
     FILE *fpt;
     FILE *fpo;
     int s, r, ch;
     printf("Enter roll number to update:");
     scanf("%d", &r);
     avl = avlrollno(r);
     if (avl == 0)
     {
      printf("Roll number %d is not Available in the file", r);
     }
     else
     {
      fpo = fopen("Record.dat", "r");
      fpt = fopen("TempFile.dat", "w");
      while (fread(&stud, sizeof(stud), 1, fpo))
      {
       s = stud.rollno;
       if (s != r)
        fwrite(&stud, sizeof(stud), 1, fpt);
       else
       {
        printf("\n\t1. Update Name of Roll Number %d", r);
        printf("\n\t2. Update Mark of Roll Number %d", r);
        printf("\n\t3. Update both Name and Mark of Roll Number %d", r);
        printf("\nEnter your choice:");
        scanf("%d", &ch);
        switch (ch)
        {
        case 1:
         printf("Enter Name:");
         scanf("%s", &stud.name);
         break;
        case 2:
         printf("Enter Mark : ");
         scanf("%f", &stud.mark);
         break;
        case 3:
         printf("Enter Name: ");
         scanf("%s", &stud.name);
         printf("Enter Mark: ");
         scanf("%f", &stud.mark);
         break;
        default:
         printf("Invalid Selection");
         break;
        }
        fwrite(&stud, sizeof(stud), 1, fpt);
       }
      }
      fclose(fpo);
      fclose(fpt);
      fpo = fopen("Record.dat", "w");
      fpt = fopen("TempFile.dat", "r");
      while (fread(&stud, sizeof(stud), 1, fpt))
      {
       fwrite(&stud, sizeof(stud), 1, fpo);
      }
      fclose(fpt);
      fclose(fpo);
      printf("RECORD UPDATED");
     }
    }
    /* FUNCTION TO SORT THE RECORD */
    void sort()
    {
        int a[20];
        int count = 0;
        int i,j,t,c;
        FILE *fpo;
        fpo = fopen("Record.dat","r");
        while(fread(&stud,sizeof(stud),1,fpo))
        {
            a[count]=stud.rollno;
            count++;
        }
       c = count;
       for(i=0;i<count-1;i++)
       {
           for(j=i+1;j<count;j++)
           {
               if(a[i]>a[j])
               {
                   t=a[i];
                   a[i]=a[j];
                   a[j]=t;
               }
           }
       }
       printf("Roll no.\tName\tMark\n\n");
       count =c;
       for(i=0;i<count;i++)
       {
           rewind(fpo);
            while(fread(&stud,sizeof(stud),1,fpo))
        {
            if(a[i]==stud.rollno)
            {
                printf("\n%d\t\t%s\t\t%2f",stud.rollno,stud.name,stud.mark);
            }
        }
    
    
       }
    }
    
    
    
    
    //    FUNCTION TO CHECK GIVEN ROLL NO IS AVAILABLE //
    int avlrollno(int rno)
    {
     FILE *fp;
     int c = 0;
     fp = fopen("Record.dat", "r");
     while (!feof(fp))
     {
      fread(&stud, sizeof(stud), 1, fp);
    
    
      if (rno == stud.rollno)
      {
       fclose(fp);
       return 1;
      }
     }
     fclose(fp);
     return 0;
    }
    
    
    //FUNCTION TO CHECK THE FILE IS EMPTY OR NOT
    int empty()
    {
        int c = 0;
        FILE *fp;
        fopen("Record.dat","r");
        while(fread(&stud,sizeof(stud),1,fp))
        {
            c = 1;
            fclose(fp);
            return c;
        }
    }
    
    
    
    
    int main()
    {
      //insert();
      //display();
      //search();
     //deletefile();
      //update();
      //sort();
    
    
      int c,emp;
      do
      {
          printf("\n\t----Select your Choice----------------\n");
          printf("\n\t1.INSERT\n\t2.DISPLAY\n\t3.SEARCH");
          printf("\n\t4.DELETE\n\t5.UPDATE\n\t6.SORT");
          printf("\n\t7.EXIT");
          printf("\n\n--------------------------------------\n");
          printf("\nEnter Your Choice:");
          scanf("%d",&c);
          printf("\n");
          switch(c)
          {
          case 1:
            insert();
            break;
          case 2:
            emp=empty();
            if(emp==0)
            {
               printf("\nTHE FILE IS EMPTY\n");
            }
            else
            {
                display();
                break;
            }
          case 3:
            search();
            break;
          case 4:
            deletefile();
            break;
          case 5:
            update();
            break;
          case 6:
            emp=empty();
            if(emp==0)
            {
               printf("\nTHE FILE IS EMPTY\n");
            }
            else
            {
                sort();
                break;
            }
          case 7:
            exit(1);
            break;
          default:
             printf("\nYour Choice is wrong\nPlease Try Again\n");
            break;
          }
    
    
    
    
      }while(c!=7);
    
    
        return 0;
    }
    and in the tutorial itself there is no fclose for while loop in sort function

  5. #5
    Registered User
    Join Date
    May 2019
    Posts
    47
    When i select display or sort function the cursor simply moves to next line and the program terminates

    see screenshot
    Some Switch not working in do-while loop-dsdg-jpg

  6. #6
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    a) First look where your breaks are in case 2 and case 6

    b) On line 247, you're using fp but fp has not been initialised

    c) You're using a global variable for no apparent reason

    d) You can use a debugger here so that you can set a breakpoint, inspect the values of variables and then step through the code line-by-line so you can see what's happening

  7. #7
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    Have you got compiler warnings turned on?! I'm not even going to look at it further until the warnings are fixed

    Code:
    sash.c:17:14: warning: format specifies type 'char *' but the argument has type 'char (*)[30]'
          [-Wformat]
     scanf("%s", &stud.name);
            ~~   ^~~~~~~~~~
    sash.c:41:8: warning: implicit declaration of function 'avlrollno' is invalid in C99
          [-Wimplicit-function-declaration]
     avl = avlrollno(r);
           ^
    sash.c:74:6: warning: implicit declaration of function 'avlrollno' is invalid in C99
          [-Wimplicit-function-declaration]
     if (avlrollno(r) == 0)
         ^
    sash.c:116:8: warning: implicit declaration of function 'avlrollno' is invalid in C99
          [-Wimplicit-function-declaration]
     avl = avlrollno(r);
           ^
    sash.c:141:18: warning: format specifies type 'char *' but the argument has type 'char (*)[30]'
          [-Wformat]
         scanf("%s", &stud.name);
                ~~   ^~~~~~~~~~
    sash.c:149:18: warning: format specifies type 'char *' but the argument has type 'char (*)[30]'
          [-Wformat]
         scanf("%s", &stud.name);
                ~~   ^~~~~~~~~~
    sash.c:223:6: warning: unused variable 'c' [-Wunused-variable]
     int c = 0;
         ^
    sash.c:253:1: warning: control may reach end of non-void function [-Wreturn-type]
    }
    ^
    sash.c:247:38: warning: variable 'fp' is uninitialized when used here [-Wuninitialized]
        while(fread(&stud,sizeof(stud),1,fp))
                                         ^~
    sash.c:245:13: note: initialize the variable 'fp' to silence this warning
        FILE *fp;
                ^
                 = NULL
    sash.c:316:9: warning: implicitly declaring library function 'exit' with type 'void (int)
          __attribute__((noreturn))' [-Wimplicit-function-declaration]
            exit(1);
            ^
    sash.c:316:9: note: include the header <stdlib.h> or explicitly provide a declaration for 'exit'

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You need to do error checking, e.g.,
    Code:
    void displayRecords(const char *filename)
    {
        FILE *fp = fopen(filename, "r");
        if (!fp)
        {
            fprintf(stderr, "Error: '%s' could not be opened.\n", filename);
            return;
        }
    
        int count = 0;
        printf("\nRoll Number\tName\tMark\n\n");
        struct student stud;
        while (fread(&stud, sizeof(stud), 1, fp) == 1)
        {
            printf("  %d\t\t%s\t%.2f\n", stud.rollno, stud.name, stud.mark);
            ++count;
        }
        if (ferror(fp))
        {
            fprintf(stderr,
                    "Error: could not finish reading '%s' due to a read error after the first %d records.\n",
                    filename, count);
        }
        fclose(fp);
    
        if (count == 0)
        {
            printf("There are no student records available.\n");
        }
    }
    Notice that:
    • I made the filename a parameter instead of hardcoding it in the function. This means that you need to change the function call, but realistically the file name should be a named constant anyway, be it local to the main function or with #define.
    • I indented by 4 spaces. This is up to you, but generally we indent by 2 to 8 spaces, or a tab, per indent level. If you choose spaces, it is usually a power of 2. 1 space is simply too little visual difference to make indentation useful.
    • I checked the return value of fopen before proceeding.
    • There's no need to sequentially name your FILE pointer fp1, fp2, etc in different functions.
    • I recorded a count of the number of records so you can display a message instead of just blank if there are no student records.
    • I used a local stud variable instead of a global variable.
    • I used the return value of fread to control the loop, but after the loop I check with ferror to differentiate between ending the loop due to EOF and ending it due to a read error.

    Are you sure that you're supposed to open and read from or write to the file in each function? If the number of records is not too large, it would be better to read the entire file into memory and then change that in-memory structure, writing to the file only when needed. If the number of records is sufficiently large... well, it is true that doing it the way you are doing it now would at least satisfy the memory requirements, but it would also be slow. My recommendation would be to use the SQLite embedded database engine, but that's beyond the scope of this exercise, which is why I think it is reasonable to assume that the number of records is sufficiently small.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    As an example of what I mean about where you've placed your breaks in the switch, what do you expect the output of the following program to be?

    Code:
    #include <stdio.h>
    
    int main(void)
    {
        int b = 0, c = 0;
        
        switch (c) {
            case  0:
                if (b == 0) {
                    puts("Hello");
                } else {
                    puts("hmm");
                    break;
                }
            case 1:
                puts("world");
                break;
            default:
                break;
        }
        
        return 0;
    }

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Read the warnings Hodor posted, then fix them.

    Code:
    int empty()
    {
        int c = 0;
        FILE *fp;
        // oops, throw away the result of fopen.
        // you can't read from it, and you cant close it either
        fopen("Record.dat","r");
        // the fread has a very high chance of getting a memory error by
        // reading from an uninitialised fp.
        while(fread(&stud,sizeof(stud),1,fp))
        {
            c = 1;
            fclose(fp);
            return c;
        }
        // oops, what gets returned here?
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 02-25-2016, 08:49 AM
  2. Help - Collect data from Switch loop inside While loop
    By James King in forum C Programming
    Replies: 15
    Last Post: 12-02-2012, 10:17 AM
  3. switch loop not working
    By dakarn in forum C Programming
    Replies: 11
    Last Post: 10-29-2008, 12:54 PM
  4. Switch structure not working
    By him61 in forum C++ Programming
    Replies: 8
    Last Post: 05-23-2007, 05:35 PM
  5. switch not working
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 01-22-2002, 07:25 AM

Tags for this Thread