我对使用无效返回的scanf有疑问。这是我正在测试的代码片段:
printf("Please enter a number\n");
while (scanf("%d",&number)==0)
{
printf("Try again.\n");
scanf("%d",&number);
}
我的推理表明,如果使用了无效的类型,我的第二个scanf应该再次询问并测试新输入的值。但是,情况并非如此,再次尝试消息永远不会停止打印,所以我必须手动终止它。我不确定为什么会这样。如果可能的话,我不想在while循环之前使用scanf,尽管我知道这是一种可能的解决方法。我很感激你对此事的任何帮助。感谢。
答案 0 :(得分:4)
scanf
不会返回错误代码。它返回成功执行的转换次数。
对于无限循环,它不消耗无法转换的输入。所以它反复尝试将相同的字符串与数字匹配。尝试使用fgets
丢弃有问题的输入。
答案 1 :(得分:0)
scanf()
可能会返回EOF
来表示输入失败。
“如果在第一次转换(如果有)之前发生输入故障,则scanf函数返回宏EOF的值。否则,scanf函数返回分配的输入项目数,可以少于为在早期匹配失败的情况下,甚至为零。“ C11 7.21.6.4
在失败的scanf("%d", ...
之后使用scanf("%d", ...
只会导致无限循环,因为每个scanf()
都试图消耗非数字,无空格和失败。要解决问题,必须消耗违规数据。
printf("Please enter a number\n");
int number;
int Count;
while ((Count = scanf("%d",&number)) != 1) {
if (Count < 0) {
exit(1); // No more input possible
}
// Some char is preventing scanf() from reading an int
scanf("%*c"); // Get it and throw away
printf("Try again.\n");
}
printf("number = %d\n", number);