我有这个:
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);
假设我的输入是 1 2 f
,然后是 a == 1
、b == 2
和 c = = 0
。更何况,isInt == 2
,这让我想知道为什么它又不正常循环了……?
最佳答案
您的代码中的问题是当 scanf(...)
返回 3 以外的数字时您做了什么(更具体地说,您没有做什么)。
目前,您的代码会继续请求输入并继续循环,而不会从输入缓冲区中获取任何内容。这当然会使您的程序进入无限循环。
为了解决这个问题,您的代码应该读取并忽略直到下一个 '\n'
字符的所有输入。这将确保每个循环迭代都取得一些进展。
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);
关于c - do-while 循环中的 scanf() 即使进行了输入测试也会导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35003965/