Reputation: 431
If user enters a character instead of a number, I want to give him another option to try once more but below code prints out "Invalid. Pls enter a number." forever if user enters a character instead of a number. Why doesn't it wait for the user to enter again? (scanf part is for that I assume)
#include <stdio.h>
long get_long(void);
int main(void) {
long start;
printf("Enter a number: ");
start = get_long();
return 0;
}
long get_long(void)
{
long num = 0;
while (scanf("%ld", &num) != 1)
{
printf("Invalid. Pls enter a number.");
}
return num;
}
Upvotes: 0
Views: 347
Reputation: 1413
like this. it executes while 2 times
int i=1;
while (i!= 2)
{ scanf("%ld", &num) ;
if(num==1)
break;
printf("Invalid. Pls enter a number.");
i++;
}
Upvotes: -1
Reputation: 47925
This is a common problem with scanf
. (The question has been asked many times; there are probably duplicate answers.) The problem is that when you type simething that isn't a valid number, scanf
fails (and returns 0), but it leaves the unmatched input on the input stream.
You have to flush the unread input somehow. One way is like this. Write the function
void flush_one_line()
{
int c;
while((c = getchar()) != EOF && c != '\n')
{ /* ignore */ }
}
This function reads and discards one line of input, up to a newline. (That is, it throws away anything and everything that the previous scanf
call didn't read.)
Then modify your original program like this:
while (scanf("%ld", &num) != 1)
{
printf("Invalid. Please enter a number.");
flush_one_line();
}
Upvotes: 0
Reputation: 122
Your logic behind the code was flawed. What you essentially did with your code is ask the while loop to work as long as correct input isn’t made.
while(incorrect input is made) {
print
}
Proper solution would be along the lines of
while(number of tries > 0) {
do operations
check for right input, if it is correct break the loop, else keep on going
decrement number of tries by one
}
Upvotes: -1