fflush() is typically used for output stream only. Its purpose is to clear (or flush) the output buffer and move the buffered data to console (in case of stdout) or disk (in case of file output stream). Below is its syntax.
fflush(FILE *ostream); ostream 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.
Can we use it for input stream like stdin?
As per C standard, it is undefined behavior to use fflush(stdin). However some compilers like Microsoft visual studio allows it allow it. How is it used in these in these compilers? While taking an input string with spaces, the buffer does not get cleared for the next input and considers the previous input for the same. To solve this problem fflush(stdin) is. used to clear the stream/buffer.
The code above takes only single input and gives the same result for the second input. Reason is because as the string is already stored in the buffer i.e. stream is not cleared yet as it was expecting string with spaces or new line. So, to handle this situation fflush(stdin) is used.
Is it good to use fflush(stdin)?
Although using “fflush(stdin)” after “scanf()” statement also clears the input buffer in certain compilers, it is not recommended to use it as it is undefined behavior by language standard. In C and C++, we have different methods to clear the buffer discussed in this post.
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Differentiate printable and control character in C ?
- Difference between %d and %i format specifier in C language
- rand() and srand() in C/C++
- Double Pointer (Pointer to Pointer) in C
- Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
- Dangling, Void , Null and Wild Pointers
- Clearing The Input Buffer In C/C++
- scanf() and fscanf() in C - Simple Yet Poweful
- getchar_unlocked() - faster input in C/C++ for Competitive Programming
- Problem with scanf() when there is fgets()/gets()/scanf() after it
- Operators in C | Set 1 (Arithmetic Operators)
- Difference between getc(), getchar(), getch() and getche()
- void pointer in C
- Bitwise Operators in C/C++
- An Uncommon representation of array elements