What is a buffer in C?
As the name suggests, a buffer is temporary storage used to store input and output commands. All input and output commands are buffered in the operating system’s buffer.
C language’s use of a buffer
C uses a buffer to output or input variables. The buffer stores the variable that is supposed to be taken in (input) or sent out (output) of the program. A buffer needs to be cleared before the next input is taken in.
Code
The following code takes multiple characters in the variables v1 and v2. However, the first character is stored in the variable, while the next character is stored in the operating system’s buffer.”
- Sample input:
a b c - Stored in variable
v1:a - Stored in buffer:
b c - Stored in
v2:b
#include<stdio.h>#include<conio.h>void main(){int v1,v2;clrscr();printf("\n Enter v1: ");scanf("%d",&v1);printf("\n Enter v2: ");scanf("%d",&v2);printf("\n v1+v2=%d ",v1+v2);getch();}
Output
Enter v1: 10
Enter v2: 20
v1+v2=30
Run the program again
Enter v1: 10 20 30
Enter v2: (nothing)
v1+v2=30
v2is automatically taken from the previous run by the buffer.
## Code using fflush(stdin)
The same input mentioned above is treated differently when the buffer is cleared.
#include<stdio.h>#include<conio.h>void main(){int v1=0;int v2=0;clrscr();printf("\n Enter v1: ");scanf("%d",&v1);printf("\n Enter v2: ");fflush(stdin);scanf("%d",&v2);printf("\n v1+v2=%d ",v1+v2);getch();}
Output
Enter v1: 10
Enter v2: 20
v1+v2=30
Run the program again
Enter v1: 10 20 30
Enter v2: (nothing)
v1+v2=10 //10+0=10
fflush(stdin) is needed to flush or clear the input buffer. It is beneficial to clear the input buffer with fflush(stdin) before taking the input using the scanf() statement.
Free Resources