I still disagree, hehe. The stream doesn't enter the error state at all. Scanf just keeps trying on wrong data, which never gets cleared. Try it out:
Original Example... Infinite loop on non digit input:
Code:
#include <stdio.h>
int main(void) {
int sel_case = 1;
while(sel_case != 0) {
if ( scanf( "%d", &sel_case ) == 1 ) {
printf("You entered: %d", sel_case);
} else {
printf("Wrong input!!");
}
}
return 0;
}
Using clearerr (still infinite loop):
Code:
#include <stdio.h>
int main(void) {
int sel_case = 1;
while(sel_case != 0) {
if ( scanf( "%d", &sel_case ) == 1 ) {
printf("You entered: %d", sel_case);
} else {
printf("Wrong input!!");
clearerr(stdin);
}
}
return 0;
}
Simulating Flushing the buffer. Error message prints only once for me.
Code:
#include <stdio.h>
int main(void) {
int sel_case = 1;
while(sel_case != 0) {
if ( scanf( "%d", &sel_case ) == 1 ) {
printf("You entered: %d", sel_case);
} else {
printf("Wrong input!!");
/* clearerr(stdin); */
while((sel_case = getchar()) != '\n' && sel_case != EOF);
}
}
return 0;
}