I'm new to c, and I don't understand why the outcome is so different whether I enter a non-numeric char or a digit. What is the fix for this? What am I doing wrong/not understanding?
while ((scanf(" %d", &option) != 1) /* non-numeric input */
|| (option < 0) /* number too small */
|| (option > 4)) /* number too large */
{
fflush(stdin); /* clear bad data from buffer */
printf("That selection isn't valid. Please try again.\n");
printf("Please enter your choice: ");
}
Output for digit out-of-range (correct):
Please enter your choice: 5
That selection isn't valid. Please try again.
Output for non-digit (infinte loop):
...
Please enter your choice: That selection isn't valid. Please try again.
Please enter your choice: That selection isn't valid. Please try again.
Please enter your choice: That selection isn't valid. Please try again.
Please enter your choice: That selection isn't valid. Please try again.
Please enter your choice: That selection isn't valid. Please try again.
...
Fix for reference (use fgets() instead of fflush()):
while ((scanf(" %d", &option) != 1) /* non-numeric input */
|| (option_text[0] < 0) /* number too small */
|| (option_text[0] > 4)) /* number too large */
{
fgets(option_text, sizeof(option_text), stdin);
printf("That selection isn't valid. Please try again.\n");
printf("Please enter your choice: ");
}