Reputation: 19
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;
}
}
Upvotes: 0
Views: 7579
Reputation: 20244
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
Upvotes: 3
Reputation: 40145
if(1!=scanf("%d", &selection)){
while(getchar() != '\n');
selection = -1;
}
Upvotes: 0