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 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.
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.”
a b c
v1
: a
b c
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(); }
Enter v1: 10
Enter v2: 20
v1+v2=30
Enter v1: 10 20 30
Enter v2: (nothing)
v1+v2=30
v2
is 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(); }
Enter v1: 10
Enter v2: 20
v1+v2=30
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.
RELATED TAGS
View all Courses