出于某种原因,如果用户输入了错误的数据类型,例如 '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);
}