if my scanf variable is a float and a user inputs a character how can i prompt them to input a number? assuming the scanf is inside a do while loop

后端 未结 2 555
花落未央
花落未央 2021-01-29 11:49

i have tried to use k = getchar() but it doesn\'t work too;

here is my code

#include
int main()
{
    float height;
    float k=0;
    do          


        
2条回答
  •  独厮守ぢ
    2021-01-29 12:11

    I wouldn't use scanf-family functions for reading from stdin in general.

    fgets is better since it takes input as a string whose length you specify, avoiding buffer overflows, which you can later parse into the desired type (if any). For the case of float values, strtof works.

    However, if the specification for your deliverable or homework assignment requires the use of scanf with %f as the format specifier, what you can do is check its return value, which will contain a count of the number of format specifiers in the format string that were successfully scanned:

    § 7.21.6.2:

    The [scanf] function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.

    From there, you can diagnose whether the input is valid or not. Also, when scanf fails, stdin is not cleared and subsequent calls to scanf (i.e. in a loop) will continue to see whatever is in there. This question has some information about dealing with that.

提交回复
热议问题