What is the use of fflush(stdin) in c programming? [closed]
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?
Solution 1:
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.
Solution 2:
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.