一、fflush()函数:更新缓存区
头文件:#include《stdio.h>
函数定义:int fflush(FILE *stream);
函数说明:调用fflush()会将缓冲区中的内容写到stream所指的文件中去.若stream为NULL,则会将所有打开的文件进行数据更新
二、fflush(stdin):刷新缓冲区,将缓冲区内的数据清空并丢弃
fflush(stdout):刷新缓冲区,将缓冲区内的数据输出到设备
请看如下代码:
//test1.c(运行环境:linux)
#inlcude<stdio.h>
int main()
{
printf("hello");
sleep(5);
printf(" world!\n");
return 0;
}
//先进入sleep后打印hello world!
//test2.c
#include<stdio.h>
int main()
printf("hello");
fflush(stdout);//将缓冲区的内容输出到设备中
sleep(5);
printf(" world!\n");
return 0;
}
//先打印hello 在进入sleep 后打印world!
三、scanf和printf
我们常用的scanf和printf都是先将数据放入缓存里,等缓存满了或是程序结束再将数据处理
四、看下fflush(stdin)
如下代码:
#include<stdio.h>
int main()
{
char a,b;
scanf("%c",&a);
//fflush(stdin);
scanf("%c",&b);
printf("%d\n",a);
printf("%d\n",b);
return 0;
}
若没有fflush(stdin);
从键盘输入:2+回车
则会将回车符赋给b
加上fflush(stdin)
输入:2+回车
则不会对b赋值