轉載自Leeboy_Wang
之前用endl一直以爲它只是一個回車換行的功能,剛剛纔知道原來endl還有一個功能使用來刷新緩衝區的。除了endl之外,c++中還有ends,flush,unitbuf,nounitbuf。爲什麼要刷新緩衝區呢?
一句話,爲了讓緩衝區的信息立即強制輸出。
如: cout << "aaa" << endl;和 cout << "aaa";都能將aaa輸出,前一個除了多了一個換行外,它的aaa是被手動強制輸出的,而後便一個aaa是系統每隔一段時間進行檢測輸出的。由於間隔比較短,讓人以爲和第一種一樣,下面有一段代碼讓你對刷新緩衝有明顯的概念。
- // test.cpp : 定義控制檯應用程序的入口點。
- //
- #include "stdafx.h"
- #include <windows.h>
- #include <iostream>
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- setvbuf( stdout, NULL, _IOLBF, 1024 ); //設置控制檯輸出爲行緩存模式,把緩衝區與流相關
- cout <<"hello world\n";
- Sleep(5000);
- cout <<"leeboy" <<endl;
- system("pause");
- return 0;
- }
// test.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
setvbuf( stdout, NULL, _IOLBF, 1024 ); //設置控制檯輸出爲行緩存模式,把緩衝區與流相關
cout <<"hello world\n";
Sleep(5000);
cout <<"leeboy" <<endl;
system("pause");
return 0;
}
所以編程要形成好的習慣,多使用endl