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:

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:

Output:

Use of fflush(stdin) in C

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:

Output:

Use of fflush(stdin) in C

Example 3:

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:

Use of fflush(stdin) in C

Pin It on Pinterest

Share This