c++输出缓冲区刷新

在c++中,io操作都是有io对象来实现的,每个io对象又管理一个缓冲区,用于存储程序读写的数据。

只有缓冲区被刷新的时候缓冲区中的内容才会写入真实的文件或输出设备上。

那么,什么情况下会刷新输出缓冲区呢,有如下五种情况:

1.程序正常结束。作为main返回工作的一部分,将清空所有的输出缓冲区。

2.在一些不确定的时候,缓冲区可能已经满了,在这种情况下,缓冲区将会在写下一个值之前刷新。

3.用操纵符显示地刷新缓冲区,如用endl。

4.在每次输出操作执行完毕后,用unitbuf操纵符设置流的内部状态,从而清空缓冲区。

5.可将输出流与输入流关联起来,在读输入流时将刷新其关联的输出缓冲区。

我们可以通过以下实例代码来加深一下理解:

	// 操纵符
	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

原文链接: https://www.cnblogs.com/rowsy/archive/2012/06/29/2838791.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    c++输出缓冲区刷新

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/53883

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午5:14
下一篇 2023年2月9日 上午5:15

相关推荐