由于某种原因,如果用户输入了错误的数据类型,例如“j”或“%”,循环将停止要求输入并继续显示“输入整数>”
一遍又一遍。如何让程序处理错误的输入?为什么输入非数字值会导致如此奇怪的行为?
#define SENTINEL 0;
int main(void) {
int sum = 0; /* The sum of numbers already read */
int current; /* The number just read */
do {
printf("\nEnter an integer > ");
scanf("%d", ¤t);
if (current > SENTINEL)
sum = sum + current;
} while (current > SENTINEL);
printf("\nThe sum is %d\n", sum);
}
最佳答案
如果 scanf()
未能找到匹配的输入,current
变量将保持不变:检查 scanf()
的返回值:
/* scanf() returns the number of assignments made.
In this case, that should be 1. */
if (1 != scanf("%d", ¤t)) break;
如果您希望在无效输入后继续接受输入,则需要从 stdin
读取无效数据,因为它将保留下来,如 pmg 所指出的。在评论中。一种可能的方法是使用格式说明符 "%*s"
读取输入但不执行赋值:
if (1 != scanf("%d", ¤t))
{
scanf("%*s");
}
else
{
}
关于c - 非数字输入导致死循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11314246/