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