关于cout输出缓冲区问题(转载和自己见解)

The endl manipulator produces a newline character, exactly as the insertion of '\n' does; but it also has an additional behavior: the stream's buffer (if any) is flushed, which means that the output is requested to be physically written to the device, if it wasn't already. This affects mainly fully buffered streams, and cout is (generally) not a fully buffered stream. Still, it is generally a good idea to use endl only when flushing the stream would be a feature and '\n' when it would not. Bear in mind that a flushing operation incurs a certain overhead, and on some devices it may produce a delay.----来自http://www.cplusplus.com/doc/tutorial/basic_io/

有关于 endl 文章说的很清楚,有两个作用:1.换行 2.刷新缓存区 一般 输出的话,有两种情况:1.刷新缓存区 2.缓存区满的时候但是一般情况下,不加endl大多数情况下,也能正常输出,是因为在系统较为空闲时候,会查看缓存区的内容,如果发现新的内容,便进行输出。

但是 你并不清楚,系统什么时候输出,什么时候不输出,与系统自身的运行状况有关。而刷新缓存区,是强制性的,绝对性的输出。不取决于系统运行状况打一个很形象的比喻, endl 相当于 一个 “要求” -- 你不得不做 (现在,立刻做) 不加 endl 的情况,相当于 一个 “建议” -- 你有空做下(你并不清楚,什么时候做,做没做)

可以亲自测试一下如下代码:
std::cout << "the normal one! " << std::endl;
std::cout << "the test! ";
sleep(20);
std::cout << "the test is over" << std::endl;
输出结果:the normal one!
the test! the test is over

而且 很明显 在测试中发现 第一行the normal one输出后,等待了较长时间 才输出第二行,而且第二行的the test! the test is over 是同时输出的。也就是说,你的第二行代码 the test! 根本就没有立刻输出,只是在缓存器中,在sleep结束后,才进行输出。

以下代码 可做 对照组 作为参考std::cout << "the normal one! " << std::endl;
std::cout << "the test! " << std::endl;
sleep(20);
std::cout << "the test is over" << std::endl;

当然,输出了则一定刷新了相应的缓冲区。
以下情况将导致缓冲区的内容被刷新:
1. 程序正常结束。结束前,将清空缓冲区
2. 缓冲区已满,则在写下一个值的时候刷新缓冲区
3. 使用endl等操纵符显式刷新缓冲区
4. 使用unitbuf刷新所有输出
5. 输入输出流绑定在一起的时候, 如cin.tie(&cout),然后cin>>操作将刷新绑定的cout缓冲区

还有就是,可能是操作系统不同和编译器不同的原因,一见<<就输出了。
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值