c++中关于cin.tie以及sync_witch_stdio同步
flush()
ostream類的一個方法,作用是將緩沖區(qū)的數(shù)據(jù)刷新到輸出文件。
/* 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); // 1soutfile.flush(); //<--}outfile.close();return 0;}執(zhí)行outfile.flush()時,把outfile緩沖區(qū)中的數(shù)據(jù)輸出到test.txt中。因此test.txt中每隔一秒新增一個數(shù)字。
若是刪除outfile.flush()這句,則100s以內(nèi)test.txt沒有增加內(nèi)容。
執(zhí)行outfile.close()是outfile緩沖區(qū)的數(shù)據(jù)被一次性flush輸出到test.txt中。
因此flush()的作用是將刷新當前緩沖區(qū)的數(shù)據(jù),將其輸出到輸出文件中。
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輸出緩沖區(qū)的數(shù)據(jù)刷新到輸出文件中。
這樣可以避免cout語句在cin之前,而命令行窗口中cin的讀入數(shù)據(jù)在cout輸出數(shù)據(jù)之前。
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而造成的輸出順序和代碼語句不一致的問題。
解綁的話,輸出結果無法預測。
總結
以上是生活随笔為你收集整理的c++中关于cin.tie以及sync_witch_stdio同步的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 求素数
- 下一篇: 2022谷歌浏览器插件FOFA Pro