rewind(stdin)清除标准输入的按键缓冲区。
fflush()清除I/O流级别的缓冲区。
先看看Microsoft给出的例子:
#include <stdio.h>
void main(void)
{
int ch ;
puts( "Input two or more chars. One is read now." );
ch = getchar();
putchar( ch );
putchar( '\n' );
puts( "The next char is taken from stdin." );
ch = getchar( );
putchar( ch );
putchar( '\n' );
rewind( stdin );
puts( "Input two or more chars. One is read now." );
ch = getchar();
putchar( ch );
putchar( '\n' );
rewind( stdin );
puts( "You must enter another char because of the rewind(stdin)" );
ch = getchar( );
putchar( ch );
putchar( '\n' );
}
再看:
int main()
{
char name[6] = {'\0'};
char password[6] = {'\0'};
int count = 0;
while(1)
{
count++;
memset(name, 0, sizeof(name));
memset(password, 0, sizeof(password));
scanf("%5[^\n]", name);
if(strcmp(name, "exit") == 0)
break;
// rewind(stdin);
fflush(stdin);
// getchar();
scanf("%5[^\n]", password);
// rewind(stdin);
fflush(stdin);
// getchar();
printf("name=[%s],password=[%s]\n",name,password);
if(count>5)break;
}
return 0;
}
若将fflush(stdin)改成rewind(stdin)测试效果相同。