[c] what is the use of fflush(stdin) in c programming

I have the following program

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char ans[8];
    int i;
    for(i=1;i<=3;i++)
    {
        printf("\n What is the unit of traffic ?");
        scanf("%s",ans);
        fflush(stdin);

        if(stricmp(ans,"Earlang")==0)
        {
            printf("\nAnswer is correct");
            exit(1);
        }
        else
            if(i<3)
            printf("\n Try Again!\n");
    }
    printf("\n Nunit of traffic is Earlang:");
}

What is the use of fflush(stdin) in this program?

This question is related to c

The answer is


It's not in standard C, so the behavior is undefined.

Some implementation uses it to clear stdin buffer.

From C11 7.21.5.2 The fflush function, fflush works only with output/update stream, not input stream.

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.


It's an unportable way to remove all data from the input buffer till the next newline. I've seen it used in cases like that:

char c;
char s[32];
puts("Type a char");
c=getchar();
fflush(stdin);
puts("Type a string");
fgets(s,32,stdin);

Without the fflush(), if you type a character, say "a", and the hit enter, the input buffer contains "a\n", the getchar() peeks the "a", but the "\n" remains in the buffer, so the next fgets() will find it and return an empty string without even waiting for user input.

However, note that this use of fflush() is unportable. I've tested right now on a Linux machine, and it does not work, for example.


it clears stdin buffer before reading. From the man page:

For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.

Note: This is Linux-specific, using fflush() on input streams is undefined by the standard, however, most implementations behave the same as in Linux.