【问题标题】:Print order when using sync_with_stdio使用 sync_with_stdio 时的打印顺序
【发布时间】:2019-09-11 22:23:09
【问题描述】:

看这个例子:

#include <iostream>
#include <stdio.h>

int main()
{
    std::ios::sync_with_stdio(false);
    std::cout << "a";
    printf("b");
    std::cout << "c";
}

在 gcc 9.2 上,我得到 acb 作为输出。我期待bac,因为如果我理解正确,std::cout 将使用它的缓冲区。为什么按这个顺序打印?

附加问题:设置std::ios::sync_with_stdio(false) 会提高性能(例如在上面的示例中)?

【问题讨论】:

    标签: c++ printf cout


    【解决方案1】:

    标准输出流的默认典型行为是行缓冲,因此输出是完全合理的。 printf 不会立即刷新,为此使用 fflush(stdout)

    对于您的第二个问题,人们会期望在不需要同步时提高性能。但是,剖析和检查总是更好,显然对于这个小sn-p来说,这并不重要。


    编辑:根据this post 更正答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      相关资源
      最近更新 更多