Reputation: 189
I have a while loop that prints a prompt for an integer. I want to error check for when the user enters a char, like 'a'. However, when I type 'a', it prints "Enter the seed: Seed must be an integer value, please try again" forever.
int getSeed() {
int scanned, seed;
while (scanned == 0) {
printf("Enter the seed: ");
scanned = scanf("%d", &seed);
if (scanned == 0) {
printf("Seed must be an integer, try again\n");
}
}
return seed;
}
How do I get this to print
Enter the seed: a
Seed must be an integer, try again
Enter the seed:
Thanks.
EDIT: Solved it, I added getchar(); after the scanf.
Upvotes: 1
Views: 501
Reputation: 1817
scanf
checks your input character and finds out that it does not match the conversion specifier, so it puts it back in the input stream.
Then in your while
loop in your code reaches to scanf
again, and the above process occurs again (since the a
you've written in input stream is still there)
So a better solution would be reading it as a character (or string) and then converting that into an integer.
Upvotes: 0