Reputation: 159
beginner programmer here learning C
Part of my code asks user for numeric input, and will go into a while loop to check if the value entered is a number or not, and if not the while loop will clear input (to stop infinite loop), and ask for a number again.
The problem is that when I clear input then ask for scanf() again in the while loop, it apparently clears it twice and I have to input the number again to get my results.
Here is part of the code in question:
int askNum()
{
int number;
int check;
printf("Enter a number: ");
check = scanf("%d", &number);
while(scanf("%d", &number) != 1)
{
printf("You've entered an incorrect number.\nEnter a number: ");
fflush(stdin);
check = scanf("%d", &number);
}
return number;
}
If someone can explain why it does this, please explain or give me some hints on how to proceed.
Thank you so much!
Upvotes: 0
Views: 891
Reputation: 141648
fflush(stdin)
is not defined by the C standard. This means that different compilers may do different things with it. Mine just ignores it completely. It's difficult to say what your compiler is doing, or why strange things might happen in association with it.
To get reliable behaviour from your program, stick to standard code.
Your loop structure is correct, however fflush(stdin)
should be replaced by some code to read and discard all of the characters that have been entered so far. Since stdin
is line-buffered by default, this means that you need to keep reading until you hit a newline and then stop; then things will be ready for another scanf("%d"
.
There's various ways to actually code this; Medinoc's answer is one; another is the [
specifier of scanf
. You also need to exit your loop if EOF happens. (Otherwise you go into an infinite loop if the input stream is closed).
Upvotes: 3
Reputation: 6608
Because your while() is wrong.
Also, fflush() is only defined for output streams. If you want portable code, you should do this instead:
void fpurge(FILE *pf)
{
int c;
while((c=fgetc(pf)) != '\n' && c != EOF)
{ }
}
It will reliably read characters until the end of the line.
Upvotes: 3