0

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;
}
  • If `scanf("%lf", &i)` returns 0, the non-numeric input remains in `stdin`. Code never consume that input, so the problem repeats. `fflush (stdin);` is UB. – chux - Reinstate Monica Dec 01 '21 at 02:42
  • 1
    "If I enter 45b, the program should print Enter correct input," --> then continue reading input until `'\n'` and see if there is non-white space. – chux - Reinstate Monica Dec 01 '21 at 02:49
  • `scanf` is a deeply imperfect function. It's especially poor at error handling. My recommendation — I don't know if this will work for you — is that if you're using `scanf`, just don't worry about improper input. If you want the ease of calling `scanf`, set aside the goal of being nice to your users if they type something wrong. If you want to do a nice job of detecting and responding to improper input, that's a worthy goal — but the only reasonable way to achieve it is by using techniques other than `scanf`. – Steve Summit Dec 01 '21 at 03:27
  • See also [this answer](https://stackoverflow.com/questions/2979209/using-fflushstdin/58884121#58884121) and [this question](https://stackoverflow.com/questions/58403537). – Steve Summit Dec 01 '21 at 03:29

1 Answers1

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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256