Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
do while循环中的scanf()即使在测试输入时也会导致无限循环_C_Scanf_Do While - Fatal编程技术网

do while循环中的scanf()即使在测试输入时也会导致无限循环

do while循环中的scanf()即使在测试输入时也会导致无限循环,c,scanf,do-while,C,Scanf,Do While,我有这个: 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); float a、b、c; 智力; 做{ puts(“请输入三个正长度:”); isInt=s

我有这个:

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);
float a、b、c;
智力;
做{
puts(“请输入三个正长度:”);
isInt=scanf(“%f%f%f”、&a、&b、&c);

}而(a代码中的问题是当
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);
do{
puts(“请输入三个正长度:”);
isInt=scanf(“%f%f%f”、&a、&b、&c);
if(isInt==EOF)break;//确保已处理EOF
如果(isInt!=3){
scanf(“%*[^\n]”);
a=b=c=-1;
继续;
}

}而(a
f
不是第三个
float
参数的有效数字输入。因此
scanf
不会返回
3
,并且无论循环多少次,它都不会解析
f
。您还必须初始化
a
b
c
(在循环开始时)为了避免未定义的行为,因为它们控制循环。您可以简单地在
if
中设置
a=0
,以确保循环将继续。这是有道理的。我必须考虑一下您的解释,但我想我明白了。您肯定解决了问题。干杯!@chux感谢您的评论!