简体   繁体   中英

Program not reading the "double" input correctly

In this C program, if I enter b as the input, the program prints Enter correct input. If I enter b45 as the input, the program again prints Enter correct input. But, if I enter 45b, the program takes 45 as the input and proceeds normally.

If I enter 45b, the program should print Enter correct input, but it is not happening.

#include <stdio.h>

 int main()
{
double i;

printf ("Enter a number. \n");
while (scanf("%lf", &i) == 0)
{
    printf("Enter correct input. \n");
    fflush (stdin);
}

printf ("%lf\n", i);

return 0;
}

Instead of reading via scanf() , read a line of user input with fgets(buf, ...) , then use strtof(buf, &endptr)) to assess if the the input was numeric and endptr to assess what is after the numeric text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM