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, the current
variable will be unchanged: check return value of scanf()
:
/* scanf() returns the number of assignments made.
In this case, that should be 1. */
if (1 != scanf("%d", ¤t)) break;
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:
if (1 != scanf("%d", ¤t))
{
scanf("%*s");
}
else
{
}
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 then sscanf()
to parse/"read" the string into the variables I was interested in.