【问题标题】:What is exact meaning of iostream is sync with ios_base::sync_with_stdioiostream 的确切含义是与 ios_base::sync_with_stdio 同步
【发布时间】:2013-07-26 04:30:05
【问题描述】:

这仅仅是意味着我们对 cout 这样的对象所做的任何事情都会与 stdout 同步(反之亦然?)。这究竟是什么意思。 stdio 是否也与 stdout 同步?

【问题讨论】:

    标签: c++ c stdout iostream


    【解决方案1】:

    如果同步关闭,C++ 流在某些情况下会更快。

    默认情况下,所有标准 C++ 流都与其各自的 C 流同步。

    例子:

    #include <iostream>
    #include <cstdio>
    using namespace std;
    int main()
    {
        cout.sync_with_stdio(false);
        cout << "Hello\n";
        printf("World\n");
        cout << "...\n";
    }
    

    输出:

    Hello
    ...
    World
    

    将其更改为true 按顺序给出默认结果。 输出:

    Hello
    World
    ...
    

    【讨论】:

    • @POW 那么,我可以得出结论吗,如果不同步,cout/printf 不能保证顺序,甚至不能保证打印出来的东西?
    • @pranitkothari 不一定,endl 即使关闭同步也会改变场景
    • @POW 当然可以,但是我要问的是没有 endl 怎么办。我知道 endl 刷新缓冲区。但是没有什么。
    【解决方案2】:

    std::cout 和 stdio(如 printf)使用的默认 ostream 是 stdout,但不一定如此。

    输出总是可以重定向到另一个目的地。引用这个:http://www.tldp.org/LDP/abs/html/io-redirection.html

    【讨论】:

    • 这是否意味着我可以使用 cout 输出到类似设备的打印机。如果可能的话,你能建议方法吗?
    • @pranitkothari 是的。问题是获取设备文件描述符并将 cout(文件描述符为 1)重定向到它。您可以在命令行中执行此操作。上面的链接可能会给你一些线索。
    【解决方案3】:

    每个 cppreference:

    Sets whether the standard C++ streams are synchronized to
    the standard C streams after each input/output operation.
    

    【讨论】:

      猜你喜欢
      • 2015-09-18
      • 1970-01-01
      • 2018-01-11
      • 2022-01-15
      • 2018-08-20
      • 2022-01-15
      • 2016-02-23
      • 2011-12-14
      • 1970-01-01
      相关资源
      最近更新 更多