clear buffer in c
To clear the buffer in C, you can use the fflush()
function. Here is an example:
#include <stdio.h>
int main() {
char buffer[100];
printf("Enter a string: ");
fgets(buffer, sizeof(buffer), stdin);
printf("String entered: %s", buffer);
fflush(stdin); // clear the buffer
printf("Buffer cleared!\n");
return 0;
}
Explanation of the code:
- First, we include the necessary header file
stdio.h
which contains thefflush()
function. - We declare a character array
buffer
with a size of 100 to store the input string. - We prompt the user to enter a string using
printf()
. - We use the
fgets()
function to read the input string from the user and store it in thebuffer
array. Thesizeof()
function is used to specify the maximum number of characters to read. - We display the entered string using
printf()
. - To clear the buffer, we use the
fflush(stdin)
statement. Thefflush()
function is used to flush the input buffer. However, it is important to note that usingfflush()
onstdin
is not defined behavior in the C standard and can have unexpected results on different systems. - We display a message indicating that the buffer has been cleared.
- Finally, we return 0 to indicate successful program execution.
Please note that using fflush(stdin)
to clear the input buffer is not a recommended practice as it is not defined behavior in the C standard. If you need to clear the input buffer, it is better to use alternative methods like reading and discarding characters until a newline character is encountered.