When does cout flush?

萝らか妹 提交于 2019-12-17 14:45:48

问题


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";

}

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;

}

回答1:


There is no strict rule by the standard - only that endl WILL flush, but the implementation may flush at any time it "likes".

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);
 }

(If you are using a Unix based OS, use sleep(1) instead - or add a loop that takes some time, etc)

Edit: 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.



来源:https://stackoverflow.com/questions/22345226/when-does-cout-flush

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!