一、原因
在linux系统下,printf函数是行缓冲式的输出。
所以,printf函数没有带’\n’是不会自动刷新输出流,直至缓存被填满。
操作系统为减少 IO操作 所以设置了缓冲区. 等缓冲区满了再去操作IO. 这样是为了提高效率。
二、解决方法
1.fflush(stdout)
刷新标准输出缓冲区,把输出缓冲区里的东西打印到标准输出设备上
#include<iostream>
#include<unistd.h>
using namespace std;
int main()
{
int k=10;
while(k--)
{
printf("[]");
fflush(stdout);
sleep(1);
}
return 0;
}
2.setvbuf(stdout,NULL,_IONBF,0);
直接将缓冲区禁止了. 它就直接输出了。
#include<iostream>
#include<unistd.h>
using namespace std;
int main()
{
setvbuf(stdout,NULL,_IONBF,0);
int k=10;
while(k--)
{
printf("[]");
sleep(1);
}
return 0;
}
Reference: