Thread: Making a switch error proof

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    27

    Making a switch error proof

    Code:
    int exercises;
    
    scanf("%d", &exercises);
    
        switch (exercises) {
    
                case 1: printf("1"); break;
                case 2: printf("2"); break;
                case 3: printf("3"); break;
                case 4: printf("4"); break;
                case 5: printf("5"); break;
                default: printf("Invalid command.\n"); break;
            
            }
        }
    With this code, if the user enters any number other than 1-5, it goes to the default.

    But if the user enters a letter, the program will go crazy.

    I know that since I'm scanning for only ints, it will only default ints and nothing else.

    Any way I can get it to default other kinds of inputs?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    It has nothing to do with the switch, and everything to do with the way scanf works. That f there means formatted. You have to give it exactly what it wants, or it's not going to work.
    Code:
    while( scanf( "%d", &exercises ) != 1 )
    {
        char buf[ BUFSIZ ] = {0};
        fgets( buf, BUFSIZ, stdin );
    }

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Take a look at the return value of scanf()...

    Code:
    int exercises;
    
    if (scanf("%d", &exercises) > 0) 
      {
      switch (exercises) {
        case 1: printf("1"); break;
        case 2: printf("2"); break;
        case 3: printf("3"); break;
        case 4: printf("4"); break;
        case 5: printf("5"); break;
        default: printf("Invalid command.\n"); break;
        }
     }
    else
      printf("Only numbers from 1 to 5 are valid");
    

  4. #4
    Registered User
    Join Date
    Mar 2011
    Posts
    27
    I like CommonTater's solution. But it still doesn't work quite right.

    My program continuously loops.

    Code:
    int main(int argc, char** argv) {
    
    int exercises;
        
    while (1) {
        printf( "1. Option 1\n"
                "2. Option 2\n"
                "3. Option 3\n"
                "4. Option 4\n"
                "5. Quit\n"
                "Choose a case: ");
    
    if (scanf("%d", &exercises) > 0)
      {
      switch (exercises) {
        case 1: printf("1\n"); break;
        case 2: printf("2\n"); break;
        case 3: printf("3\n"); break;
        case 4: printf("4\n"); break;
        case 5: exit(EXIT_SUCCESS); break;
        default: printf("Invalid command.\n"); break;
        }
     }
    else
      printf("Only numbers from 1 to 5 are valid");
    }
    }
    If the user doesn't enter an int, it will print "Only numbers from 1 to 5 are valid" and the options over and over again.

  5. #5
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,164
    That's because you left the crap in the read buffer. quzah had the better solution. But together, they both make a full solution.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  6. #6
    Registered User
    Join Date
    Mar 2011
    Posts
    27
    How do I keep 'the crap' out of the read buffer?

    I tried quzah's option at first, but then when I tried to enter something, it would go to a new line. So I guess I wasn't putting it inside my code correctly.

    edit: And I didn't understand what quzah's code did. I only understood CommonTater's.
    Last edited by never_lose; 06-13-2011 at 11:43 PM.

  7. #7
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,164
    Quote Originally Posted by never_lose View Post
    How do I keep 'the crap' out of the read buffer?

    I tried quzah's option at first, but then when I tried to enter something, it would go to a new line. So I guess I wasn't putting it inside my code correctly.
    I guess you are correct.


    Quote Originally Posted by never_lose View Post
    edit: And I didn't understand what quzah's code did. I only understood CommonTater's.
    This is a help forum, isn't it? Ask.
    Start with 'what does fgets() do?'
    Last edited by WaltP; 06-14-2011 at 02:13 AM.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by WaltP View Post
    I guess you are correct.
    No he isn't.


    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Try reading in a line (using fgets()) and then interpret the contents of the line (possibly by using sscanf()) to see if it actually has the desired input.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by never_lose View Post
    I like CommonTater's solution. But it still doesn't work quite right.

    My program continuously loops.
    That's because there's stuff in the input buffer you aren't clearing out....

    Code:
    int main(int argc, char** argv) {
    
    int exercises;
        
    while (1) {
        printf( "1. Option 1\n"
                "2. Option 2\n"
                "3. Option 3\n"
                "4. Option 4\n"
                "5. Quit\n"
                "Choose a case: ");
    
    if (scanf("%d", &exercises) > 0)
      switch (exercises) {
        case 1: printf("1\n"); break;
        case 2: printf("2\n"); break;
        case 3: printf("3\n"); break;
        case 4: printf("4\n"); break;
        case 5: exit(EXIT_SUCCESS); break;
        default: printf("Invalid command.\n"); break;
        }
    else
      { 
         printf("Only numbers from 1 to 5 are valid");
         while (getchar()); 
       }  
      }
    }

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    It's depressing to see so many senior posters getting this so horribly wrong
    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.

  12. #12
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Salem View Post
    It's depressing to see so many senior posters getting this so horribly wrong
    OK.... what's your solution?

  13. #13
    'Allo, 'Allo, Allo
    Join Date
    Apr 2008
    Posts
    639
    Quote Originally Posted by Salem View Post
    It's depressing to see so many senior posters getting this so horribly wrong
    It's like Rumsfeld all over again. "There are things we know, we don't know. There are things we don't know we know."

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > OK.... what's your solution?
    Well you could start by working out when getchar() would return 0, so it could exit this loop...

    > while (getchar());

    fgets() is part of the answer, but nobody seems to be checking for EOF yet.
    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.

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    There's nothing wrong with my first post. He wanted it to read a number, it reads a number and ignores everything else. You'll notice I didn't signal trap either. Why? Because that wasn't part of the OP's request.

    "But he could have used CTRL C!"

    So what?


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. switch case error. Can anyone help?
    By brack in forum C Programming
    Replies: 4
    Last Post: 02-28-2011, 03:30 PM
  2. Error proofing my switch statement.
    By Shamino in forum C++ Programming
    Replies: 10
    Last Post: 01-04-2008, 04:38 PM
  3. Switch error
    By liats80 in forum C Programming
    Replies: 6
    Last Post: 11-26-2007, 05:53 AM
  4. Switch stat error
    By Emperor128 in forum C++ Programming
    Replies: 3
    Last Post: 04-05-2006, 05:07 PM
  5. switch or if else....how to check for error
    By clear in forum C Programming
    Replies: 1
    Last Post: 04-30-2003, 01:24 PM