The answer to this is that fflush(stream) is only formally defined for output streams, so fflush(stdout) is OK, but fflush(stdin) is not.

The purpose of fflush(stream) is to make the operating system flush any buffers to the underlying file. For an example of a legitimate use, students often have problems like “my prompt doesn't appear!” if they do something like:

printf("Enter a number: ");

However, they find that this works just fine:

printf("Enter a number:\n");

Of course, they don't want a newline after their prompt, so they have a bit of a problem.

The reason for this is that the output to stdout is buffered by the OS and the default behavior is (often) only to actually write the output to the terminal when a newline is encountered. Adding an fflush(stdout) after the printf() solves the problem:

printf("Enter a number: ");
fflush(stdout);

Now, working by analogy, people often think that fflush(stdin) should discard any unused input, but if you think about it a little bit that doesn't make much sense. What does it mean to “flush” an input buffer? Where is it “flushed” to? If you flush an output buffer, the output is sent to the underlying file or the terminal, where it would eventually wind up anyway, but where would input “eventually end up anyway”? There's no way of knowing! What should the behavior be if the input stream data comes from a file or a pipe or a socket? It isn't at all clear for input streams what the behavior of fflush() should be, but it's very clear for output streams in all cases. Hence, fflush() is only defined for output streams.

The reason why the erroneous use of fflush(stdin) became commonplace is that, many years ago, a few operating systems did implement a scheme where it worked as many people expected, discarding unused input. Microsoft DOS is a good example. Surprisingly, modern versions of Linux also implement fflush() for input streams.

The right thing to do with “extra” unwanted terminal input is simply to read it and do nothing with it. This is almost as easy as calling fflush(stdin), works everywhere, and doesn't rely on formally undefined behavior.

The C standard says:

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.

POSIX says (also explicitly defers to C standard):

If stream points to an output stream or an update stream in which the most recent operation was not input, fflush() shall cause any unwritten data for that stream to be written to the file, ...

But the Linux manpage says:

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. The open status of the stream is unaffected.

Answer from Emmet on Stack Overflow
🌐
YouTube
youtube.com › zeenat hasan academy
fflush function in C in Hindi Lec-72|C Programming Tutorial in Hindi - YouTube
fflush function in C in Hindi#Cprogramming #zeenathasan #fflushinC
Published   May 13, 2018
Views   16K
Top answer
1 of 2
47

The answer to this is that fflush(stream) is only formally defined for output streams, so fflush(stdout) is OK, but fflush(stdin) is not.

The purpose of fflush(stream) is to make the operating system flush any buffers to the underlying file. For an example of a legitimate use, students often have problems like “my prompt doesn't appear!” if they do something like:

printf("Enter a number: ");

However, they find that this works just fine:

printf("Enter a number:\n");

Of course, they don't want a newline after their prompt, so they have a bit of a problem.

The reason for this is that the output to stdout is buffered by the OS and the default behavior is (often) only to actually write the output to the terminal when a newline is encountered. Adding an fflush(stdout) after the printf() solves the problem:

printf("Enter a number: ");
fflush(stdout);

Now, working by analogy, people often think that fflush(stdin) should discard any unused input, but if you think about it a little bit that doesn't make much sense. What does it mean to “flush” an input buffer? Where is it “flushed” to? If you flush an output buffer, the output is sent to the underlying file or the terminal, where it would eventually wind up anyway, but where would input “eventually end up anyway”? There's no way of knowing! What should the behavior be if the input stream data comes from a file or a pipe or a socket? It isn't at all clear for input streams what the behavior of fflush() should be, but it's very clear for output streams in all cases. Hence, fflush() is only defined for output streams.

The reason why the erroneous use of fflush(stdin) became commonplace is that, many years ago, a few operating systems did implement a scheme where it worked as many people expected, discarding unused input. Microsoft DOS is a good example. Surprisingly, modern versions of Linux also implement fflush() for input streams.

The right thing to do with “extra” unwanted terminal input is simply to read it and do nothing with it. This is almost as easy as calling fflush(stdin), works everywhere, and doesn't rely on formally undefined behavior.

The C standard says:

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.

POSIX says (also explicitly defers to C standard):

If stream points to an output stream or an update stream in which the most recent operation was not input, fflush() shall cause any unwritten data for that stream to be written to the file, ...

But the Linux manpage says:

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. The open status of the stream is unaffected.

2 of 2
20

fflush(stdin) invokes undefined behaviour.

fflush() is defined only for output streams. You should not do it.


On Unix, Ctrl-Z sends a TSTP signal (SIGTSTP) which by default causes the process to suspend execution.

Discussions

What is the use of fflush(stdin) in c programming? - Stack Overflow
For input streams, fflush() discards ... 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. ... in the above program , even though fflush(stdin) is not written ... More on stackoverflow.com
🌐 stackoverflow.com
c - Why should I use fflush(stdin) in this program? - Stack Overflow
I know that it is use to clean the keyboard buffer, but I don't understand when/why I need to use it or if I really need to. For example, into this code that I made for my class, it only works if... More on stackoverflow.com
🌐 stackoverflow.com
Why is fflush(stdin) not clearing input buffer??
fflush is meant for output streams, not stdin. "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." https://port70.net/~nsz/c/c11/n1570.html#7.21.5.2p2 In particular, for glibc 's implementation of fflush: "For input streams associated with seekable files (e.g., disk files, but not pipes or terminals), fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application." https://man7.org/linux/man-pages/man3/fflush.3.html More on reddit.com
🌐 r/C_Programming
7
7
June 10, 2024
¿Por qué necesito fflush(stdout) cuando uso printf en un ...
🌐 r/C_Programming
🌐
Reddit
reddit.com › r/learnprogramming › [c] can someone please explain fflush(stdin) to me?
r/learnprogramming on Reddit: [C] Can someone please explain fflush(stdin) to me?
July 1, 2015 -

I understand that this command flushes out the input stream but what does it mean by "flushing the stream".

🌐
GeeksforGeeks
geeksforgeeks.org › c language › use-fflushstdin-c
Use of fflush(stdin) in C - GeeksforGeeks
September 15, 2023 - 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.
🌐
Quora
quora.com › What-is-fflush-stdin-in-a-C-language
What is fflush (stdin); in a C language? - Quora
Answer (1 of 14): Undefined behavior. I have read most of the answers for this question, and they all say its to clear the input stream. To them I say, start reading the C standard before giving out such answers. Though [code ]fflush()[/code] function is used to clear a stream, using it on [cod...
🌐
TutorialsPoint
tutorialspoint.com › use-of-fflush-stdin-in-c
Use of fflush(stdin) in C
June 24, 2020 - The function fflush(stdin) is used to flush the output buffer of the stream. It returns zero, if successful otherwise, returns EOF and feof error indicator is set. Here is the syntax of fflush(stdin) in C language,
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › c_function_fflush.htm
C Library - fflush() function
The C library fflush() function flushes the output buffer of a stream.This function forces a write of all buffered data for the given output or update stream to the file. When applied to an input stream, its behavior is undefined.
🌐
Quora
quora.com › Why-do-we-use-the-functions-fflush-stdin-and-fflush-stdout-in-c
Why do we use the functions fflush(stdin) and fflush(stdout) in c? - Quora
Answer (1 of 6): Let us first understand the different I/O functions that the standard library provides and their relationship to each other. Output For formatted output, you have fprintf / printf / and their variants. For string output, you have fputs. For output of uninterpreted data i.e. raw ...
🌐
IncludeHelp
includehelp.com › c-programs › fflush-function-in-c-language-with-example.aspx
fflush() function in C language with Example
#include <stdio.h> #include <stdlib.h> int main() { //Initialize the file pointer FILE* f; //Take a array of characters char ch[100]; //Create the file for write operation f = fopen("includehelp.txt", "w"); printf("Enter five strings\n"); for (int i = 0; i < 4; i++) { //take the strings from the users scanf("%[^\n]", &ch); //write back to the file fputs(ch, f); //every time take a new line for the new entry string fputs("\n", f); //except for last entry.Otherwise print the last line twice //clear the stdin stream buffer //fflush(stdin); //if we don't write this then after taking string //%[^\n
🌐
Physics Forums
physicsforums.com › other sciences › programming and computer science
Is it Safe to Use fflush(stdin) in C Programming? • Physics Forums
January 13, 2010 - The discussion centers on the use of fflush(stdin) in C programming, highlighting that its behavior is undefined according to the C standard. While some compilers, like MSVC, may clear the input buffer when fflush(stdin) is called, others, such as GCC, may do nothing or return an error.
🌐
Sololearn
sololearn.com › en › Discuss › 570915 › what-is-the-use-of-fflushstdin-in-c-programmingi-know-here-c-is-not-included
What is the use of fflush(stdin) in c programming(i know here c is not included) | Sololearn: Learn to code for FREE!
As the word suggests it allows you to flush your stdin (standard input), that is to say your keyboard. When you use a program and give input by keyboard, the keys you press are stored in a kind of box (ideally) and they wait to be consumed by some function or someting like that... If you press some keys while using a programm and nothing consume them , they stay there and if you want to delete them from there, you can use fflush(stdin) function which clear the box the same way your toilet does when you flush it...
🌐
Coddingbuddy
coddingbuddy.com › article › 52619841 › how-can-i-clear-stdin-in-a-c-progam
How can I clear stdin in a C progam?
C Language in Hindi, Though fflush() function is used to clear a stream, using it on stdin is simply undefined behavior in C, as the function is defined formally for only output streams fflush function in C in Hindi Lec-72 - Duration: 5:09. Zeenat Hasan 8,265 views.
🌐
Linux Hint
linuxhint.com › fflush-stdin-in-c-programming
What Does fflush(stdin) Do in C Programming – Linux Hint
In C programming, the fflush(stdin) function is used to clear the input buffer memory of any data that may still be stored. It does this by freeing up any memory associated with the standard input stream, known as stdin, which is the default input used for reading any data from command line ...
🌐
Quora
quora.com › What-is-the-use-of-fflush-stdin-in-C-or-C
What is the use of fflush(stdin) in C or C++? - Quora
Answer (1 of 4): It is used to flush output buffers. Normal write operations, for example, will buffer output until a time that is convenient for the computer. As far as the program is concerned, the data is gone (for example, written to the ...
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 21878-fflush-stdin.html
fflush(stdin)
July 18, 2002 - Sorry for being a pain... just curious. R ... It's as I described. It is in your case removing any pending input. Thus, your scanf call snips off the 9.9, leaving the remainder in the input stream / buffer. You next call fflush(stdin) (which you should actually use), and it clears the buffer.
🌐
OnlineGDB
question.onlinegdb.com › 16865 › fflush-stdin-meaning-in-c
fflush(stdin) meaning? in c - OnlineGDB Q&A
The purpose of fflush() is to clear or flush the buffer. However, according to the C standard: · fflush() is only guaranteed to work on output streams (like stdout)
🌐
Scaler
scaler.com › home › topics › fflush() in c
fflush() in C - Scaler Topics
May 4, 2023 - The function fflush(stdin) is used to flush the output buffer of the stream. It returns zero, if successful otherwise, returns EOF and of error, the indicator is set.
Top answer
1 of 2
4

Actually the professor is wrong if speaking of standard C. According to the standard, calling fflush on an input stream (such as stdin) is undefined behaviour.

However, in many implementations (including Linux†, OS X, various BSDs, etc.) fflush(stdin) discards any input that has been buffered but not yet consumed. This non-standard feature is used in your program to clear the trailing newline left in the input buffer by the previous scanf.

man fflush on Linux is kind enough to mention that this is non-standard (although the wording doesn't quite suggest undefined behaviour):

The standards do not specify the behavior for input streams.

Meanwhile the C11 standard under 7.21.5.2 The fflush function says:

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.

† According to comments this non-standard behaviour may not work on Linux despite man fflush claiming that it should.

2 of 2
0
  1. You should not use fflush(stdin) in a C program. It's not well-defined. It's not portable.

  2. You should not need to use fflush(stdin) in a C program. The only time this need comes up, sadly, is when progammers are learning C and using scanf a lot and getting bin by one of scanf's notoriousl difficulties. Simply put, stop using scanf and the "need" to flush input goes away. Or, insert extra calls to getchar, or loops that read and discard input up to a newline, as described elsewhere.