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;
}
CodePudding user response:
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.