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;
        printf("\n What is the unit of traffic ?");

            printf("\nAnswer is correct");
            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 tagged with c

~ Asked on 2013-08-11 09:10:48

The Best Answer is


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

Some implementation uses it to clear stdin buffer.

From C11 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.

~ Answered on 2013-08-11 09:12:57


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.

~ Answered on 2013-08-11 09:12:22

Most Viewed Questions: