Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

}

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;

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
311 views
Welcome To Ask or Share your Answers For Others

1 Answer

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<<"
";
   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 " or something similar.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...