0

Okay It now loops correctly but when you give it an input e.g. '2' it just goes to the default case.

 print_Menu() {
        while ( 1 )
    {
        printf("=============================================\n");
        printf("MENU\n");
        printf("=============================================\n");
        printf("1. Do stuff\n2. Do more stuff\n3. Do even more stuff\n4. Quit\n");
        printf("Choose an option: ");

        scanf(" %s*", &selection);


        switch (selection) {
            case 1:
                /*do your thing for option 1*/
                printf("thing 1\n");
                break;
            case 2:
                /*do your thing for option 2*/
                printf("thing 2\n");
                break;
            case 3:
                /*do your thing for option 3*/
                printf("thing 3\n");
                break;
            case 4:
                /*do your thing for option 3*/
                printf("quiting app\n");
                exit(0);
                break;
            default:
                printf(" Invalid selection\n");
               // print_Menu();
                break;
        }
      } 
2
  • 1
    By incorrect input you mean an integer that is not in the range 1-4, or do you mean something that is not an integer? Commented Nov 15, 2014 at 13:39
  • 2
    Do you really want to call the function recursively on the default case? Commented Nov 15, 2014 at 13:39

2 Answers 2

3

Just add

scanf("%*s");

in the default case to clear the invalid character(s) from the input buffer.The * tells scanf to scan a string and then discard it.

scanf fails to get an integer and returns 0 when you enter any other thing other than an integer. This data does not get consumed by the scanf and hence, remains in the stdin.When scanf is called for the second time,it sees the character which you typed in earlier and then again fails to read an integer.This will then result in an infinite loop

Sign up to request clarification or add additional context in comments.

8 Comments

@Sparky3295 And don't call printMenu() recursively.
@Sparky3295 ,Also specify the return type before the function definition.(I think you need void there)
Okay that worked, but now when I enter an option it just goes straight to the default.
@Sparky3295 , What did you enter?
when I entered an option e.g 1, it would just call the default case and not case 1. I've used a while loop now so that I don't recursively call print_Menu() and that seems to do what I want it to.
|
0
if(1!=scanf("%d", &selection)){
    while(getchar() != '\n');
    selection = -1;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.