c++輸出緩衝區刷新

在c++中,io操作都是有io對象來實現的,每個io對象又管理一個緩衝區,用於存儲程序讀寫的數據。

只有緩衝區被刷新的時候緩衝區中的內容纔會寫入真實的文件或輸出設備上。

那麼,什麼情況下會刷新輸出緩衝區呢,有如下五種情況:

1.程序正常結束。作爲main返回工作的一部分,將清空所有的輸出緩衝區。

2.在一些不確定的時候,緩衝區可能已經滿了,在這種情況下,緩衝區將會在寫下一個值之前刷新。

3.用操縱符顯示地刷新緩衝區,如用endl。

4.在每次輸出操作執行完畢後,用unitbuf操縱符設置流的內部狀態,從而清空緩衝區。

5.可將輸出流與輸入流關聯起來,在讀輸入流時將刷新其關聯的輸出緩衝區。

我們可以通過以下實例代碼來加深一下理解:


[cpp] 
// 操縱符 
cout << "hi!" << flush; // flushes the buffer, adds no data 
cout << "hi!" << ends; // inserts a null, then flushes the buffer 
cout << "hi!" << endl; // inserts a newline, then flushes the buffer 
 
// unitbuf操縱符 
cout << unitbuf << "first" << " second" << nounitbuf; 
 
// unitbuf會在每次執行完寫操作後都刷新流 
 
// 上條語句等價於 
cout << "first" << flush << " second" << flush; 
 
// nounitbuf將流恢復爲正常的,由系統管理的緩衝區方式 
 
// 將輸入輸出綁在一起 
// 標準庫已經將cin和cout綁定在一起 
// 我們可以調用tie()來實現綁定 
cin.tie(&cout); // the library ties cin and cout for us 
ostream *old_tie = cin.tie(); 
cin.tie(0); // break tie to cout, cout no longer flushed when cin is read 
cin.tie(&cerr); // ties cin and cerr, not necessarily a good idea! 
cin.tie(0); // break tie between cin and cerr 
cin.tie(old_tie); // restablish normal tie between cin and cout 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章