【发布时间】:2012-07-04 01:57:42
【问题描述】:
由于某种原因,如果用户输入了错误的数据类型,例如 '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);
}
【问题讨论】:
-
scanf()在第一个非数字字符处停止。它将该字符保留在缓冲区中。下一次循环时,角色仍然存在,scanf停止。下一次循环时,角色仍然存在,scanf停止。下一次循环... ... -
由于
SENTINEL宏的值,这段代码甚至不应该编译。可能你想要#define SENTINEL 0。 -
那只是一个错字。就像你在原始程序中写的那样,我在上面修复了它。