For some reason, if the user inputs the wrong data type, such as ‘j’ or ‘%’, the loop will stop asking for input and will keep displaying "Enter an integer >" over and over. How can I make the program handle bad inputs? And why does entering a non-numerical value cause such strange behavior?
#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()fails to find a matching input, thecurrentvariable will be unchanged: check return value ofscanf():If you wish to continue accepting inputs after an invalid input, the invalid data needs to be read from
stdinas it will remain, as pointed out by pmg in the comments. One possible way would be to use the format specifier"%*s"that reads the input but performs no assignment: