issue with switch statement

This is a discussion on issue with switch statement within the C Programming forums, part of the General Programming Boards category; HI there, I implemented a menu with a switch statement with which one can navigate through the different options I ...

  1. #1
    Registered User bluetxxth's Avatar
    Join Date
    Feb 2010
    Location
    sweden
    Posts
    43

    issue with switch statement

    HI there,

    I implemented a menu with a switch statement with which one can navigate through the different options I offered, which coincide, in turn, with the cases on the switch statement.

    I intended the line that contains 'default' for the menu to return to the initial state, that is where it asks me for the options I want to enter.

    However instead of returning to the default state in which I can select the option that I want, the program terminates. Everything else works fine in the program... I thought about implementing a goto statement but this would be in violation of 'good programming practices' .... what can I do?

    Also in order for the program to continue until the end of the process I removed the break; statements within the switch statement. Is this orthodox? I am thinking that perhaps I should have used if statements and do whiles... any suggestions?

    Thank you


    Code:
    int main(int argc, char** argv) {
    
        int option;
    
        menu();
    
    
      printf("Enter option: "); // this is the state in which I want the program when finishing <<<HERE
          scanf("%d",&option);
    
      switch (option) {
    
          case 1:printf("Create employee\n");
        fill_staff(); // takes index from user 
        employee_create(); // fills an array with index above
    
          case 2: printf("Enter employee data\n");
        for (d = 1; d <= emp_num; d++)
        employee_data(); //enter data for the employees created
    
        case 3:printf("Print employee list\n");
        for (d = 1; d <= emp_num; d++)
        print_employee(); //prints the array of employees
       
        default: printf("\n\n\nEnter option: "); //Return back to the original state and continue choosing options -- THIS IS WHERE THE PROBLEM IS <<<
          scanf("%d",&option);
      }
     
        return (EXIT_SUCCESS);
    }
    Last edited by bluetxxth; 02-24-2010 at 01:56 AM. Reason: added explanation

  2. #2
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,425
    your program ends after the switch block because there is no loop, a condition i in the switch is matched, or default is used, then the program flow will just continue beyond the end of the closing switch braces, ie exit.

    you need to wrap it in a loop, use a while loop starting above the switch and ending after the close brace.
    set the condition in the while loop to "while option is not equal to 'whatever'"
    this way it will continue requesting options until number 5 or whatever you decide to exit on is pressed.
    you need to cover possibility of invalid input in your scanf statements, which can also lead to infinite loops..

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,497
    It's normally
    Code:
    case 1:
       // some stuff
       break;
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    Registered User
    Join Date
    Feb 2009
    Posts
    68
    Another way to look at doing the program:


    Code:
    do
    {
    
    printf("If you would like to do this, enter 1);
    printf("if you would like to do that, enter 2);
    printf("to exit the program, enter 0);
    scanf("%i", &x);
    
    
    if(x = 1)
    ....
    if(x = 2)
    ....
    
    }
    while(x != 0);


    I have no idea how "menu" works, so don't shoot me if you have to use a switch statement. :P

  5. #5
    Registered User bluetxxth's Avatar
    Join Date
    Feb 2010
    Location
    sweden
    Posts
    43

    issue with switch statement

    Thank you guys...!! I will try the suggestion with the loop statement right away..

    BR,

    blue

  6. #6
    Registered User bluetxxth's Avatar
    Join Date
    Feb 2010
    Location
    sweden
    Posts
    43

    probem with switch statement

    I re-wrote the code to include the suggestion...However what I get now is that when I select an option it is permanently stuck in that option. If I select 'create employee' which corresponds to case 1 then it permanently asks me to enter employees. Did I do the while statement right? How do I move on to other cases? I post the updated code below

    Code:
    int main(int argc, char** argv) {
    
        int option;
    
        menu();
    
    
      printf("Enter option: ");
          scanf("%d",&option);
    
    
      while (option!=0){
    
      switch (option) {
    
          case 1:printf("Create employee\n");
        fill_staff(); // takes index from user
        employee_create(); break;// fills an array with index above
    
          case 2: printf("Enter employee data\n");
          for (d = 1; d <= emp_num; d++)
        employee_data(); break;//enter data for the employees created
    
        case 3:printf("Print employee list\n");
        for (d = 1; d <= emp_num; d++)
        print_employee();break; //prints the array of employees
    
         case 4:printf("Exit program: ");
                option = 0;break;
    
        default: printf("\n\n\nEnter option: "); //Return back to the original state and continue choosing options
          scanf("%d",&option);break;
            }
    
      }
     
        return (EXIT_SUCCESS);
    }
    Last edited by bluetxxth; 02-24-2010 at 02:55 AM. Reason: missing explanation

  7. #7
    Registered User GL.Sam's Avatar
    Join Date
    Aug 2009
    Posts
    88
    default: printf("\n\n\nEnter option: "); //Return back to the original state and continue choosing options
    scanf("%d",&option);break;
    Remove this and get scanf out of switch, in the end of while block. Also, case 4 is not needed and will not actually work since you would assign option a value of 0 and then immediately overwrite it with a user's response.
    Last edited by GL.Sam; 02-24-2010 at 03:17 AM.
    The only good is knowledge and the only evil is ignorance.
    ~Socrates

  8. #8
    Registered User
    Join Date
    Feb 2010
    Posts
    37

    Try like this

    You need to get the option every time and based on that you are going to do the stuffs na.
    So
    Code:
    while(option != 0)
    {
             printf("Enter the option");
             scanf("%d",&option);
             switch(option)
             {
                      case 1:
                                //stuffs.....
                      case 2:
                               //stuffs...
                         .
                         .
                         .
                      case n:
                               //stuffs
                               break
                      default:
                              printf("Invalid option");
                              break;
               }
    }

  9. #9
    Registered User
    Join Date
    Feb 2009
    Posts
    68
    Another minor thing I see is that you just say:

    Code:
    int option;
    You want to set it equal to something other than zero. It may work 99% of the time, but that 1% of the time may be the 1% that your professor grades your assignment.

  10. #10
    Registered User bluetxxth's Avatar
    Join Date
    Feb 2010
    Location
    sweden
    Posts
    43

    issue with switch statement

    Hi GL SAM,

    I think I am understanding you wrong... By removing the default line out of the switch I get an error. '... main.c:118: error: 'default' label not within a switch statement...'

    If this is what you meant? I paste the code which does not work and thereafter the one that does work...

    Code:
    int main(int argc, char** argv) {
    
        int option;
    
        menu();
    
    
        printf("Enter option: ");
        scanf("%d", &option);
    
    
        while (option != 0) {
    
            switch (option) {
    
                case 1:printf("Create employee\n");
                    fill_staff(); // takes index from user
                    employee_create(); break;// fills an array with index above
    
                case 2: printf("Enter employee data\n");
                    for (d = 1; d <= emp_num; d++)
                        employee_data();break; //enter data for the employees created
    
                case 3:printf("Print employee list\n");
                    for (d = 1; d <= emp_num; d++)
                        print_employee(); break;//prints the array of employees
    
                case 4:printf("Exit program: ");
                    option = 0;break;
    
    
            }
            default: printf("\n\n\nEnter option: "); //Return back to the original state and continue choosing options <<< THIS IS MOVED OUT OF THE SWITCH STATEMENT
            scanf("%d", &option);break;
        }
    
        return (EXIT_SUCCESS);
    }




    If I, on the other side, remove the break; statements I get the desired result.... why is that? I paste the code that works below:




    Code:
    int main(int argc, char** argv) {
    
        int option;
    
        menu();
    
    
        printf("Enter option: ");
        scanf("%d", &option);
    
    
        while (option != 0) {
    
            switch (option) {
    
                case 1:printf("Create employee\n");
                    fill_staff(); // takes index from user
                    employee_create(); // fills an array with index above
    
                case 2: printf("Enter employee data\n");
                    for (d = 1; d <= emp_num; d++)
                        employee_data(); //enter data for the employees created
    
                case 3:printf("Print employee list\n");
                    for (d = 1; d <= emp_num; d++)
                        print_employee(); //prints the array of employees
    
                case 4:printf("Exit program: ");
                    option = 0;
    
                default: printf("\n\n\nEnter option: "); //Return back to the original state and continue choosing options
                    scanf("%d", &option);
            }
    
        }
    
        return (EXIT_SUCCESS);
    }
    Last edited by bluetxxth; 02-24-2010 at 03:28 AM. Reason: added clarification

  11. #11
    Registered User bluetxxth's Avatar
    Join Date
    Feb 2010
    Location
    sweden
    Posts
    43

    issue with switch statement

    Quote Originally Posted by madmax2006 View Post
    Another minor thing I see is that you just say:

    Code:
    int option;
    You want to set it equal to something other than zero. It may work 99% of the time, but that 1% of the time may be the 1% that your professor grades your assignment.

    I take notice ;-)

  12. #12
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Just a bit of tweaking:


    Code:
    int main(int argc, char** argv) {
    
        int option = 1;
    
        menu();
    
    
        while (option != 0) {
    
            printf("Enter option: ");
            scanf("%d", &option);
            getchar();  //pulls off the remaining newline
    
            switch (option) {
    
                case 1:printf("Create employee\n");
                    fill_staff(); // takes index from user
                    employee_create(); break;// fills an array with index above
    
                case 2: printf("Enter employee data\n");
                    for (d = 1; d <= emp_num; d++)
                        employee_data();break; //enter data for the employees created
    
                case 3:printf("Print employee list\n");
                    for (d = 1; d <= emp_num; d++)
                        print_employee(); break;//prints the array of employees
    
                case 4:printf("Exit program: ");
                    option = 0;break;
    
    
                 default: printf("\n I don't have that option available, please try again");
            }
        }
    
        return (EXIT_SUCCESS);
    }

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,636
    You might want to consider something like this:
    Code:
    int option = menu();
    while (option != OPTION_QUIT) {
        switch (option) {
            /* handle valid options */
        default:
            /* print error message concerning invalid option */
        }
        option = menu();
    }
    My idea is that handling the menu consists of two parts: printing it, and reading the menu option. Thus, menu() does both (possibly by calling other functions that handle the two individual parts), then returns the option read.

    Now, instead of printing the menu in the default case, you print an error message. It is always the case that as long as the option is not an option to quit (i.e., the option matches the OPTION_QUIT constant), the menu will be printed and the next option read.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    Registered User bluetxxth's Avatar
    Join Date
    Feb 2010
    Location
    sweden
    Posts
    43

    issue with switch statement

    Quote Originally Posted by laserlight View Post
    You might want to consider something like this:
    Code:
    int option = menu();
    while (option != OPTION_QUIT) {
        switch (option) {
            /* handle valid options */
        default:
            /* print error message concerning invalid option */
        }
        option = menu();
    }
    My idea is that handling the menu consists of two parts: printing it, and reading the menu option. Thus, menu() does both (possibly by calling other functions that handle the two individual parts), then returns the option read.

    Now, instead of printing the menu in the default case, you print an error message. It is always the case that as long as the option is not an option to quit (i.e., the option matches the OPTION_QUIT constant), the menu will be printed and the next option read.
    Thank you much laser light as a matter of fact thank you all!

    This seems a more sophisticated way to make the menu...

    I guess that for this I would have to have two functions one to read and one to print... and perhaps even some parameters right?

    Blue

  15. #15
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,425
    i think your original menu() just displayed the options right? laserlight has shown that you could use the function to return the option chosen, thus this could be your 'read' function. Then you could create a 'write' function that carries option as an integer argument. then all the print functions you previously wrote in the switch cases could be carried out in that new function.

    you could use the switch cases to just set a variable to show that the option is valid, then call the write function at the end based on that (use an if statement to control as you wont want to call write() if the default case is matched and option was invalid. un less you want write() to display your error messages too)

    or just call write() in each switch case.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Mutli Switch statement help
    By elwad in forum C Programming
    Replies: 9
    Last Post: 05-09-2009, 03:19 AM
  2. Switch statement / default:
    By kcpilot in forum C Programming
    Replies: 4
    Last Post: 12-02-2008, 02:14 PM
  3. Replies: 17
    Last Post: 11-11-2007, 12:30 PM
  4. Equivalent of less than in a switch statement?
    By Diamonds in forum C++ Programming
    Replies: 5
    Last Post: 10-14-2002, 07:14 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21