Reputation: 351
I need to check if the user entered a integer in a scanf() (in C). I have this code:
do {
srs = scanf("%d", &x);
} while (!srs);
If I enter a number it works and continues with the program, but if I enter a char, it just asks me for input again. Though, if then of this I enter a correct integer, it don't break the loop.
Upvotes: 0
Views: 307
Reputation: 39000
When you don't enter the number first, it leaves the non-numeric character on the input stream for the next call to pick up. So you get in an infinite loop.
You should be using fgets
to read a whole line of input, then sscanf
on that input line.
do {
char line[512];
fgets(line,512,stdin);
srs = sscanf(line,"%d", &x);
} while (!srs);
Upvotes: 1