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 

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