c++中关于cin.tie以及sync_witch_stdio同步

flush()

ostream类的一个方法,作用是将缓冲区的数据刷新到输出文件。

    /* Flushing files (flush manipulator) */
    #include <ostream>      /* std::flush*/
    #include <fstream>      // std::ofstream
    #include <bits/stdc++.h>
    int main () {
        std::ofstream outfile ("test.txt");
        for (int n=0; n<100; n++)
        {
            outfile << n;
            _sleep(1000); // 1s
            outfile.flush(); //<--
        }
        outfile.close();
        return 0;
    }

执行outfile.flush()时,把outfile缓冲区中的数据输出到test.txt中。因此test.txt中每隔一秒新增一个数字。
若是删除outfile.flush()这句,则100s以内test.txt没有增加内容。
执行outfile.close()是outfile缓冲区的数据被一次性flush输出到test.txt中。
因此flush()的作用是将刷新当前缓冲区的数据,将其输出到输出文件中。

cin.tie()

cin is tied to the standard output stream cout (see ios::tie), which indicates that cout’s buffer is flushed (see ostream::flush) before each i/o operation performed on cin.

没有绑定的输入输出流的i/o操作互相独立,互不影响。cin和cout绑定后,cin之前会将cout输出缓冲区的数据刷新到输出文件中。
这样可以避免cout语句在cin之前,而命令行窗口中cin的读入数据在cout输出数据之前。

ios::sync_with_stdio(default=true)

If the streams are synchronized, a program can mix iostream operations with stdio operations, and their observable effects are guaranteed to follow the same order as used in the thread.

iostream 和cstdio绑定。这样为了避免混用printf和cout而造成的输出顺序和代码语句不一致的问题。
解绑的话,输出结果无法预测。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值