问题
I am using what scanf() returns when it gets what is expects or when it doesn't. What happens is it gets stuck in the
while()` loop.
To my knowledge test = scanf("%d", &testNum);
returns a 1 if it receives a number and a 0 if not.
My code:
#include<stdio.h>
int main(void) {
while (1) {
int testNum = 0;
int test;
printf("enter input");
test = scanf("%d", &testNum);
printf("%d", test);
if (test == 0) {
printf("please enter a number");
testNum = 0;
}
else {
printf("%d", testNum);
}
}
return(0);
}
回答1:
The problem here is, upon encountring an invalid input, (a character, for example), the incorrect input is not consumed, it remains in the input buffer.
So, in the next loop, the same invalid input is again read by scanf()
.
You need to clean up the buffer after identifying incorrect input. A very simple approach will be,
if (test == 0) {
printf("please enter a number");
while (getchar() != '\n'); // clear the input buffer off invalid input
testNum = 0;
}
That said, either initialize test
, or remove printf("%d", test);
, as test
being an automatic variable, unless initialized explicitly, contains indeterminate value. Attempt to use that can invoke undefined behavior.
That said, just to be nit-picky, return
is not a function, don't make it look like one. It's a staement, so return 0;
is much more soothing to the eyes and much less confusing, anyway.
来源:https://stackoverflow.com/questions/39537753/why-inside-a-loop-scanf-with-d-does-not-wait-for-the-user-input-in-case-it-r