-2

So today I am trying to find a way to check if this input is a number. I cant find a way to make this code work so far. If I enter a number, the while loops ends, which is my intention. But, if I enter anything else, the code SHOULD print the printf once and then reprompt me for input (via the scanf statement back at the top of loop). But it instead prints the printf statement infinitely. How can I fix this?

float num1;
while (scanf("%f",&num1)==0)
    {
        printf("Invalid input. Please enter a number: ");
    }
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
King Sutter
  • 61
  • 2
  • 4
  • 11

1 Answers1

1

If scanf fails to preform the requested conversion, it will leave the input stream unchanged. So while your check is correct, you need to clean the input stream of the erroneous input before re-attempting to read a number again.

You can do it with scanf itself and and the input suppression modifier:

float num1;
while (scanf("%f",&num1)==0)
{
  printf("Invalid input. Please enter a number: ");
  scanf("%*s");
}

%*s will instruct scanf to parse the input as though it's attempting to convert a string of characters (removing characters in the process from the stream), but thanks to the asterisk, it won't attempt to write it anywhere.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458