什么时候cout flush? [英] When does cout flush?
问题描述
我知道 endl
或调用 flush()
会清除它。我也知道当你在 cout
后调用 cin
时,它也会刷新。并且当程序退出时。还有其他情况, cout
刷新吗?
I know endl
or calling flush()
will flush it. I also know that when you call cin
after cout
, it flushes too. And also when the program exit. Are there other situations that cout
flushes?
我只是写了一个简单的循环, ,但我可以看到它正在打印到屏幕上。为什么?谢谢!
I just wrote a simple loop, and I didn't flush it, but I can see it being printed to the screen. Why? Thanks!
for (int i =0; i<399999; i++) {
cout<<i<<"\n";
}
此外,完成时间与 endl
两者约7秒。
Also the time for it to finish is same as withendl
both about 7 seconds.
for (int i =0; i<399999; i++) {
cout<<i<<endl;
}
推荐答案
没有标准的严格规则 - 只有 endl
将冲洗,但实施可以随时刷新喜欢。
There is no strict rule by the standard - only that endl
WILL flush, but the implementation may flush at any time it "likes".
当然,在400K以下的所有数字的总和是6 * 400K = 2.4MB,这不太可能适合缓冲区,并且循环快足够运行,你不会注意到每个输出之间需要一段时间。尝试这样:
And of course, the sum of all digits in under 400K is 6 * 400K = 2.4MB, and that's very unlikely to fit in the buffer, and the loop is fast enough to run that you won't notice if it takes a while between each output. Try something like this:
for(int i = 0; i < 100; i++)
{
cout<<i<<"\n";
Sleep(1000);
}
(如果您使用的是基于Unix的操作系统,请使用 sleep(1)
改为 - 或添加一个需要一些时间的循环等)
(If you are using a Unix based OS, use sleep(1)
instead - or add a loop that takes some time, etc)
编辑:应该注意,这不是保证显示任何差异。我知道在我的Linux机器上,如果你没有在这种特定类型的场景中刷新,它不会输出任何东西 - 但是,一些系统可能会冲洗\\\
或类似的东西。
It should be noted that this is not guaranteed to show any difference. I know that on my Linux machine, if you don't have a flush in this particular type of scenario, it doesn't output anything - however, some systems may do "flush on \n" or something similar.
这篇关于什么时候cout flush?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!