因此,该程序在循环内接受三个值,一个 int、一个 float 和一个 char。 当它要求用户输入整数并且他们写.. 比方说,“House”程序陷入无限循环。
#include <stdio.h>
int main(void){
int i;
float f;
char c;
while(i!=99){
printf("Enter an int, a float and a char separated by commas: ");
int count = scanf("%d,%f,%c",&i,&f,&c);
printf("Int is: %d, Float is: %1.f, Char is: %c",i,f,c);
if (count != 2){
fflush(stdin);
printf("\nerror\n");
}
}
return 0;
}
最佳答案
scanf()
留下未被解释为要读取的数据的字符,因此在下一次迭代中,scanf()
尝试再次读取字符并再次失败,那么就会造成死循环。fflush(stdin);
是未定义的行为,不要使用它。i!=99
中使用了未初始化的i
,这也是未定义的行为。
试试这个:
#include <stdio.h>
int main(void){
int i=0;
float f=0.0f;
char c=' ';
while(i!=99){
printf("Enter an int, a float and a char separated by commas: ");
int count = scanf("%d,%f,%c",&i,&f,&c);
printf("Int is: %d, Float is: %1.f, Char is: %c",i,f,c);
if (count != 3){ /* adjusted to match the scanf */
int dummy;
while((dummy=getchar())!='\n' && dummy!=EOF); /* skip one line */
printf("\nerror\n");
if (dummy == EOF) break; /* there won't be any more input... */
}
}
return 0;
}
关于c - 获取与预期不同的值在循环中运行。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33855336/