I have a very simple code segment where there is a do while loop with a switch case which goes as follows:
do {
printf("Enter Choice\n");
scanf("%d", &choice);
switch(choice) {
case 1: printf("1 selected");
break;
case 2: printf("exit");
break;
default: printf("wrong input");
break;
}
} while (choice != 2);
In this piece of code if by accident I enter a character instead of a number the program goes haywire looping indefinitely and doesnt even take the input.
I know this can be corrected if I insert
if(isdigit(choice))
before getting into switch case. But my question is why does it happen in the first place.
Shouldn’t it go to default case and ask for input again?
If
scanfcan’t match input with the format specifier, it leaves it in the buffer. So the next time around it still won’t match and so on. In other words, it doesn’t eat what it can’t match. You must check the value returned byscanf, the number of matched items, to make sure the input was expected.Alternatively, to skip unwanted stuff, you could try (untested):
This should discard anything that’s not a digit before trying to read a decimal integer.