由于某种原因,如果用户输入了错误的数据类型,例如“j”或“%”,循环将停止要求输入并继续显示"Enter an integer >"
一遍又一遍。如何让程序处理错误的输入?为什么输入非数字值会导致如此奇怪的行为?
#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);
}
If 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 https://stackoverflow.com/users/25324/pmg在评论中。一种可能的方法是使用格式说明符"%*s"
读取输入但不执行赋值:
if (1 != scanf("%d", ¤t))
{
scanf("%*s");
}
else
{
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)