【问题标题】:c++ stream buffer and flushc ++流缓冲区和刷新
【发布时间】:2020-07-24 09:47:11
【问题描述】:
#include <iostream>
#include <chrono>
#include <thread>

using namespace std::chrono;


int main() {
    std::cout << "hello";
    std::this_thread::sleep_for(2s);
    std::cout << "world"<<std::endl;
}

我正在使用 Visual Studio 2019。
我希望上面的代码在 2 秒后打印 helloworld,但 hello 会在 2 秒前在控制台中显示(即当我运行程序时立即显示),并且世界会在 2 秒后显示。
我最近阅读了有关缓冲区的内容,并且知道只有在缓冲区已满后才能在控制台中显示文本。 我们可以使用\nmanupulatorscin.强制刷新缓冲区

但为什么在这个特定示例中我没有看到所需的行为?
cout 不是在使用缓冲区吗?
是否为每个字符刷新?

【问题讨论】:

  • 我没有复制这个:wandbox.org/permlink/PCKs3MfduGHlVd83(我之前添加了一些文本以查看编译结束的时刻,helloworld 在两秒钟后出现)。缓冲和刷新取决于很多事情,我认为你不能得到一个单一的答案。对于它的价值,std::cout 确实使用了缓冲,并且不太可能在每个字符之后刷新它(这将非常低效)。也许您的编译器注意到睡眠并决定刷新,或者它只是在非优化构建中的每个 &lt;&lt; 运算符调用后刷新?
  • 我希望上面的代码在 2 秒后打印 hello before 和 world ,但是 hello 会在 2 秒前在控制台中显示 你的措辞令人困惑。您是否期望 hello and 世界会在 2 秒后出现?
  • 我也无法重现。 helloworld 像@Yksisarvinen 写的那样在 2 秒后一起出现(Linux 上的 g++ 8)。
  • 我刚刚尝试了您的 MCVE。 1. 在 cygwin/bash/g++ 中:行为就像(您可能已经)预期的那样:helloworld 在 2 秒后出现。 2.在Windows Console/cmd.exe/cl(VS2017的cl)中:hello立即出现,world after 2 s。 3.我再次在cygwin/bash中执行了test.exe(2.内置)。现在,helloworld 像 1 一样立即出现(2 秒后)。
  • @Scheff 我已经编辑了我的问题以使其更清楚。当我运行程序时,你好会立即显示,世界 ID 仅在 2 秒后显示

标签: c++ buffer


【解决方案1】:

标准中没有严格规定何时刷新缓冲区。

就像 cmets 中提到的 @Yksisarvinen 一样,刷新不受编译器影响,而是受操作系统影响。此外\n 并不总是触发刷新。如果cout 要去一个终端,它通常是行缓冲的,因此你可以通过\n 强制刷新。

更多信息请访问: When does cout flush?Does new line character also flush the buffer?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-14
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 2010-11-01
    • 2018-10-25
    • 2015-08-10
    • 1970-01-01
    相关资源
    最近更新 更多