the C language empties the input buffer use in standard input (stdin) Cases
Program 1:
Function: First enter a number, then enter a character, output hello bit
#include <stdio.h>
int Main ()
{
int num = 0;
Char ch = "' ;
scanf ("%d", &num);
scanf ("%c", &ch);
printf ("Hello bit\n");
System ("pause");
return 0;
}
Results:
7
Hello bit
Please press any key to continue ...
Analysis: There is no input character, the output is directly " Hello bit "Because when you click Enter ('\ n'), it is equivalent to entering a character, then we need to clear the buffer processing
Program 2:
#include <stdio.h>
int Main ()
{
int num = 0;
Char ch = "' ;
scanf ("%d", &num);
/*fflush (stdin); * * //Empty buffer error prone, not recommended
/*SCANF ("%*[^\n]"); *///is not good, easy to fail
setbuf (stdin, NULL); //enable the stdin input stream to be converted from the default buffer to no buffer
scanf ("%c", &ch);
printf ("Hello bit\n");
System ("pause");
return 0;
}
Results:
5
J
Hello bit
Please press any key to continue ...
Program 3:
Function: First enter a number, then enter a character, output hello bit
#include <stdio.h>
#define clear_buf() \
int c = 0; \
while ((c = GetChar ())! = EOF && c! = ' \ n ') \
{ \
; \
}
int Main ()
{
int num = 0;
Char ch = "' ;
scanf ("%d", &num);
Clear_buf ();
scanf ("%c", &ch);
printf ("Hello bit\n");
System ("pause");
return 0;
}
Results:
8
S
Hello bit
Please press any key to continue ...
Analysis: Program 3 recommended to use, keep using GetChar () gets the characters in the buffer until the obtained C is "\ n" or the end of file is EOF, this method perfectly clears the input buffer and is portable
This article is from the "Rock Owl" blog, please be sure to keep this source http://10742111.blog.51cto.com/10732111/1720583
C: C language emptying input buffers for use in standard input (stdin) cases