问题
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