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);
}
One way would be to read the input into a string and then convert the string to the data type you want.
My C is a bit rusty, but I recall using
fgets()
to read the string, and thensscanf()
to parse/"read" the string into the variables I was interested in.If
scanf()
fails to find a matching input, thecurrent
variable 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
stdin
as 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: