Use of fflush(stdin) in C
Use of fflush(stdin) in C
Usually, fflush() is only used for the output stream. The purpose is to clean (or flush) the output buffer and transfer the buffered data into the terminal (in the case of stdout) or disk (throughout the case of file output). Its syntax is below.
Syntax:
The syntax for the fflush function in the C Language is:
int fflush(FILE *stream);
Can we use it for streaming inputs like stdin?
Using fflush(stdin) is an unspecified behavior pattern, as per C standard. However, some compilers like the visual studio in Microsoft permit this. How are those compilers used in these? A buffer does not get cleared over the next input even when taking an integer number with spaces and discusses the previous input for the same. fflush(stdin) is used to resolve this issue to clear this same stream and buffer.
Example 1:
/* C program for condition demonstration in which flush() is only necessary In some compilers, */ #include <stdio.h> #include<stdlib.h> int main() { char str[15]; int k; for (k=0; k<5; k++) { scanf("%[^\n]s", str); printf("%s\n", str); // fflush(stdin); } return 0; }
Output:
The above code only needs to take a single input and produces a certain result for the second input. The reason is that the string has been stored in the buffer, i.e., the stream also isn't cleared yet as the string with spaces or new line was expecting. So fflush(stdin) is used to manage this case.
Example 2:
/* C illustration program with flush(stdin) The above program just worked perfectly In some compilers, such as visual studio Windows. */ #include <stdio.h> #include<stdlib.h> int main() { char str[24]; int k; for (k = 0; k<6; k++) { scanf("%[^\n]s", str); printf("%s\n", str); // used to clear the buffer // and accept the next string fflush(stdin); } return 0; }
Output:
Example 3:
#include <stdio.h> #include <string.h> int main () { char buffer[1024]; memset( buffer, '\0', sizeof( buffer )); fprintf(stdout, "Going to set full buffering on\n"); setvbuf(stdout, buffer, _IOFBF, 1024); fprintf(stdout, "This is www.tutorialandexample.com\n"); fprintf(stdout, "This output will go into buffer\n"); fflush( stdout ); fprintf(stdout, "And this will come up during programming\n"); fprintf(stdout, "will come after sleeping 10 seconds\n"); sleep(10); return(0); }
Now let us compile the above program and execute it, which will generate the desired results. (So this program continues buffering into the output in buffer until it encounters the first call to fflush() after which the output is buffered again and rests for 10 seconds at last. Before the program comes out, it sends the remaining output to the STDOUT.
Output: