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:

  1. First, we include the necessary header file stdio.h which contains the fflush() function.
  2. We declare a character array buffer with a size of 100 to store the input string.
  3. We prompt the user to enter a string using printf().
  4. We use the fgets() function to read the input string from the user and store it in the buffer array. The sizeof() function is used to specify the maximum number of characters to read.
  5. We display the entered string using printf().
  6. To clear the buffer, we use the fflush(stdin) statement. The fflush() function is used to flush the input buffer. However, it is important to note that using fflush() on stdin is not defined behavior in the C standard and can have unexpected results on different systems.
  7. We display a message indicating that the buffer has been cleared.
  8. 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.