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?
(B) stdin argument is passed to fflush() The fflush() method clears the I/O buffer associated with the open file given by the FILE reference argument. If somehow the file was opened to writing, fflush() will write the document's contents.
The stdin is the short form of the “standard input”, in C programming the term “stdin” is used for the inputs which are taken from the keyboard either by the user or from a file. The “stdin” is also known as the pointer because the developers access the data from the users or files and can perform an action on them.
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With