int n = 0;
int temp = 0;
while ((temp != 1) || (n <= 0)){
puts("enter array count");
temp = scanf("%d", &n);
printf("\n%d\n", temp);
}
我需要检查输入值,因为它必须是一个整数并且是&gt; 0
scanf
返回成功设定值的计数,如果它不是整数,则返回0。
所以问题是,当我输入除数字之外的任何字符时,它会启动非完成周期
为什么?
答案 0 :(得分:2)
当您为scanf("%d", &n);
键入无效字符(例如字符)时,scanf
会失败,返回0,会将无效数据留在stdin
。在下一次迭代中,scanf
会看到stdin
中存在的此无效数据再次失败,并且会重复此过程。
修复是在循环的每次迭代中清除stdin
。添加
int c;
while((c = getchar()) != '\n' && c != EOF);
或
scanf("%*[^\n]");
scanf("%*c");
在scanf
之后清除stdin
。