×

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:

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:

/* 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:

Use of fflush(stdin) in C

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:

Use of fflush(stdin) in C


Related Topics

Static function in C

The functions in the C programming language are by default global. This means the programmer can easily access the function which is outside from the file where it was initially...

3 minutes read.

Fibonacci series in C

We have learned about the Fibonacci series in mathematics. For a quick recap, A Fibonacci series is the sequence of numbers following a certain pattern i.e., the next number should...

3 minutes read.

Decimal to Binary in C

What is a decimal number? A decimal number is a number represented in the decimal number system. This system of binary conversion uses base 10 to represent numbers, i.e. the digits...

3 minutes read.

What is Linked List in C

Linked list Similar to an array, a linked list is a linear data structure that stores a chain of nodes with two fields of memory in each node. Where first memory...

7 minutes read.

Type Conversion in the C

The process of changing one data type to another in the C programming language is known as "type conversion." The type conversion method is only executed on data types that...

4 minutes read.

GCD of Two Numbers in C

The GCD means the greatest common divisor of two or more integers, it is also called as hcf. The gcd returns the greatest integer of the given two integers that...

3 minutes read.

Find Day from Day in C Without using function

Introduction: In the given article, I find daily in C without using functions. It takes 365 days for the earth to revolve around the sun. It will be close to...

3 minutes read.

Multiplication Table in C

Displaying table up to 10 #include <stdio.h> int main() {     int num, i = 1;     printf("     Enter any Number:");     scanf("%d", &num);     printf("Multiplication table of %d: ", num);  ...

1 minute read.

Merge Sort in C

The merge sort follows the principle of the divide and conquers algorithm. Firstly it divides the input of an array into two halves and then calls itself for the two...

4 minutes read.

Assignment Operator Program in C

An assignment operator is a symbol used to assign a value to a variable in a programming language. The assignment operator is often the equal symbol (=) in programming languages....

12 minutes read.

Use of Structure in C

We can usually use arrays in C programming to store elements of the same data type. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

Runtime vs compile time in C

In the C programming language, the often used terms in every step consist of compile time and runtime. The compile time is referred to the source code that will be...

4 minutes read.

Prime Number code in C

Prime Number Programs in C language In this tutorial, we will learn how to check whether the given number is a prime number or not, and how to print all the...

4 minutes read.

Goto and Labels in C

Introduction Goto in C: The goto statement is known as the jump statement in C. The goto is used to transfer the control of a program to a predefined label. The goto...

3 minutes read.

How to lock top row in Excel

How to lock top row in excel While working with an Excel spreadsheet, the user utilizes the rows and columns to enter the details under various headings. Sometimes while scrolling the...

4 minutes read.

C Decision control statement

Decision Making C conditional statements are used to specify one or more conditions. The statements will be executed if the condition becomes true otherwise alternative statement will be executed if the...

3 minutes read.

While-Loop in C

Syntax of While Loop The syntax that has been used for the while loop in C programming language is: while (termination condition) {   // the body of the loop  } Working of While-Loop Initially, we...

3 minutes read.

C String Manipulation programs without using Library Functions

C string manipulation programs without using Library Functions The string is the character list, and typically we operate with library functions to read and print the entire string, but here you...

6 minutes read.

Pseudo Code in C

Pseudo code in C can be referred to as a simple way or method to write programming code or program algorithm in English. A pseudocode is an informal representation of...

4 minutes read.

Remove an element from an array in C

A collection of objects or pieces of the same data type stored in a single memory block is known as an array. A data structure called an array is used...

3 minutes read.