0

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:  ");
}
Manu
  • 3
  • 3
  • `fflush(stdin)` is not a standard thing so it may not work. Instead skip till the next whitespace or EOL with `fgetc` or `fgets`. – Yakov Galka Apr 15 '20 at 16:44
  • Yes ```fgets(option, sizeof(option), stdin)``` worked and fixed it. The suggested question explained it, thanks! – Manu Apr 15 '20 at 16:49

0 Answers0