Why does fflush(stdin) fail to work ?

   #include <stdio.h>
    #include <stdlib.h>
    int main(void)
    {
        double number;
        while (scanf("%lf", &number) != 1)
        {   
            printf("Error\n");
           
        }   
        printf("%lf\n", number);
    
    
        return 0;
    }

Look at the above code.

I want the program to stop for me to type something again every time scanf gets an invalid value.

Never ending loop occurs.

I know the first invalid value has not been cleared and is still in the buffer.

So I use fflush(stdin).

    #include <stdio.h>
    #include <stdlib.h>
    int main(void)
    {
        double number;
        while (scanf("%lf", &number) != 1)
        {   
            printf("Error\n");
            fflush(stdin);
        }   
        printf("%lf\n", number);
    
    
        return 0;
    }

However, it keeps failing to work.

Why am I wrong and how can I modify the code to make that work?

When an invalid character is entered the code goes into an endless loop. It seems this line:

while (scanf("%lf", &number) != 1)

Is essentially the same as this:

while(1)

It may check the condition, but in this case that condition will never change. You could that same check in an if statement so it is only checked once. Or use the while(1) in that loop with breaks to jump out of the loop when needed. You might want to look into fgets. The scanf function is great for learning, but can introduce potential security problems. Hope that helps.

It is learnt that scanf will not consume any input if the first byte in input buffer itself does not match the format. So, when an invalid input is entered it will remain in input buffer until some one(getchar() ?) consume it.

A call to fflush () flushes data held in an output stream buffer to the underlying file; it doesn't flush input streams. The return value from scanf () has told you that you don't have a floating point number at the start of the stream, but there is still unmatched data sitting in the buffer. If there wasn't any unmatched data, it would have reported EOF. Another call to scanf () with a different format might successfully match a hexadecimal input value, a character value, or a string value. If you replace the fflush(stdin); with another scanf () to skip over a string value (i.e. scanf("%*s"); ), you might get what you want... Or, you might not. You haven' t given a very clear description of what sort of input might be entered by your input source.

Note, however, that an EOF or an I/O error condition on the input stream will still leave you with an infinite loop. And, if you're dealing with humans typing input, you need to perform much better error handling.