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>void main(){
int a,b;
printf("\n Enter a value: ");
scanf("%d",&a);
printf("\n Enter b value: ");
scanf("%d",&b);
printf("\n a+b=%d ",a+b);
getch();
}
OutputEnter a value: 1Enter b value: 2
a+b=3
In the implementation, when we need to remove standard input buffer data then go for flushall() or fflush() function.
flushall() − It is a predefined function present in stdio.h. by using flushall we can remove the data from I/O buffer.
fflush() − It is a predefined function in "stdio.h" header file which is used to clear either input or output buffer memory.
fflush(stdin) − It is used to clear the input buffer memory. It is recommended to use before writing scanf statement.
fflush(stdout) − It is used for clearing the output buffer memory. It is recommended to use before printf statement.