今天看到有段代码在输出的时候用到了cout << n << std::flush; 从名称来看知道std::flush的作用肯定是刷新缓冲区,但是测试一下他与cout << n; 感觉没有任何区别。于是只能问度娘了。果然颇有收获。cout << n; 是系统每隔一段时间进行检测输出的。但是由于间隔比较短,让人以为和没有flush一样。而且还知道了,cout << n << std::endl 的作用不止是回车换行,他还有刷新缓冲区的作用。c++中还有ends,unitbuf,nounitbuf等用来刷新缓冲区,简单来说刷新缓冲区的作用就是为了让缓冲区的信息立即强制输出。
下面有一段代码让你对刷新缓冲有明显的概念:
#include <windows.h>
#include <iostream>
using namespace std;
int main()
{
setvbuf(stdout, NULL, _IOLBF, 1024); //设置控制台输出为行缓存模式,把缓冲区与流相关
cout << "hello world\n" << flush;
cout << "hello world\n";
Sleep(5000);
cout << "leeboy" << endl;
system("pause");
return 0;
}
所以编程要形成好的习惯,记得刷新缓冲区。