zoukankan      html  css  js  c++  java
  • sync_with_stdio(false)的副作用

    sync_with_stdio()的一个特性
    sync_with_stdio() 用处是“关闭同步”,从而加快cin与cout的效率。
    在部分机子上如果开了这个函数cin和cout跑的还比printf和scanf快。
    但是用了sync_with_stdio(false)之后不能与printf和scanf同用,否则会出错。
    最近调试的时候发现的:

    #include<iostream>
    #include<cstdio>
    using namespace std;
    int main()
    {
        ios::sync_with_stdio(false);
        cout<<"1
    ";
        printf("2
    ");
        cout<<"3
    ";
        printf("4
    ");
    }
    

    运行结果是:

    2
    4
    1
    3
    

    可以发现开了ios::sync_with_stdio(false)之后,printf函数被提前了,而且这与它在代码中具体出现的位置无关。
    至于为什么,据说是C++为了兼容C语言,保证程序在使用std::printfstd::cout的时候不发生混乱(不发生上述情况),将输出流绑到了一起,也就是用了sync_with_stdio()函数:

    如果不绑到一起(也就是开个ios::sync_with_stdio(false)),会造成指针读取的混乱,因此输出顺序混乱。
    不过在测试的时候我并没有发现cin与scanf的不兼容(出于安全,还是别一起用)。

    转载自:https://www.cnblogs.com/LZShuing-xuan/p/12584916.html

    没有未来的未来不是我想要的未来
  • 相关阅读:
    用python将博客园的文章爬取到本地
    2016.7.9
    2016.7.8
    2016.7.7
    2016.7.5
    2016.7.4
    2016.7.3
    2016.7.2
    2016.6.28
    2016.6.27
  • 原文地址:https://www.cnblogs.com/Little-Turtle--QJY/p/13832888.html
Copyright © 2011-2022 走看看