问题
I'm working on a tic-tac-toe final project. I ask the user to print the box number he would like to fill in, and then i use integer err to obtain the return value of scanf. Scanf should return the number of integers it has read in this case, and I am asking for one integer to be read, so as long as err != 1, it should go into the while loop. This, however, isn't working.
printf("\nBox number: ");
int boxNumber, err;
err = scanf("%d", &boxNumber);
while (err != 1) {
printf("\nWrong input.");
printf("\nBox number: ");
err = scanf("%d", &boxNumber);
}
When a non-integer is inputted, the output is:
Wrong Input.
Box number:
In a non-stop loop. The line where scanf is then called again for the user to input a value is as though never run.
I have no idea what the problem is. Please help.
回答1:
After the first scanf()
fails, the non-integer remains in the input stream and prevents any following from succeeding, while staying forever.
You need to get rid of the non-scannable lingering input.
See these articles for choosing your favorite method:
http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
How to read / parse input in C? The FAQ
来源:https://stackoverflow.com/questions/50272231/validating-input-using-scanfs-return-value-isnt-working