Clearing input buffer in C/C++

C++ProgrammingServer Side Programming

The function fflush(stdin) is used to flush or clear the output buffer of the stream. When it is used after the scanf(), it flushes the input buffer also. It returns zero if successful, otherwise returns EOF and feof error indicator is set.

Here is the syntax of fflush(stdin) to clear the input buffer in C language,

int fflush(FILE *stream);

Here is an example of fflush(stdin) to clear the input buffer in C language,

Example

 Live Demo

#include <stdio.h>
#include<stdlib.h>

int main() {
   char s[20];

   printf("Enter the string : \n", s);
   scanf("%s\n", s);
   printf("The entered string : %s", s);
     
   fflush(stdin);
   return 0;
}

Output

Here is the output

Enter the string : helloworld
The entered string : helloworld
raja
Published on 23-Oct-2018 16:06:57
Advertisements