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而造成的输出顺序和代码语句不一致的问题。
解绑的话,输出结果无法预测。