Here is a snippet from my code
scanf("%d", &s);
while(s!=1 && s!=2) {
if(scanf("%d", &s) != 1) {
show_warning(); //just print some info msg
}
}
The idea is to execute show_warning function only if user enter something different of 1,2 and entered value to be only integer.
With the code above it jumps in infinity loop. How to fix that ?
The problem is that the failed input operation doesn’t extract any characters from the stream (and you’ll keep reading the invalid input over and over), so you have to empty the input manually. For example:
As I suggested in the other question, if you use
fgetsfrom the start to always read one line and process it later, you overcome this problem.(The same philosophy is true in C++: read the whole line first so the input stream can move on, and process the line later to see if its valid.)