While loop to validate input is a number in C?

This question already has an answer here:

  • Why inside a loop, scanf() with %d does not wait for the user input in case it received an invalid input previously? 1 answer

  • 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.

    链接地址: http://www.djcxy.com/p/72200.html

    上一篇: get()如何在scanf之后工作?

    下一篇: while循环来验证输入是C中的数字吗?