问题
I have this:
float a, b, c;
int isInt;
do {
puts("Please enter three positive lengths:");
isInt = scanf(" %f %f %f", &a, &b, &c);
} while(a <= 0 || b <= 0 || c <= 0 || isInt != 3);
Let's say my input is 1 2 f
, then a == 1
, b == 2
, and c == 0
. Even more, isInt == 2
, which makes me wonder why it doesn't loop normally again...?
回答1:
The problem in your code is what you do (more specifically, what you do not do) when scanf(...)
returns a number other than 3.
Currently, your code continues asking for input and loops on, without taking anything from the input buffer. This, of course, makes your program go into an infinite loop.
In order to fix this issue your code should read and ignore all input up to the next '\n'
character. This would make sure that each loop iteration makes some progress.
do {
puts("Please enter three positive lengths:");
isInt = scanf(" %f %f %f", &a, &b, &c);
if (isInt == EOF) break; // Make sure EOF is handled
if (isInt != 3) {
scanf("%*[^\n]");
a = b = c = -1;
continue;
}
} while(a <= 0 || b <= 0 || c <= 0);
Demo.
来源:https://stackoverflow.com/questions/35003965/scanf-in-a-do-while-loop-causes-infinite-loop-even-with-test-of-input