1

I had searched for "buffer" in c++ quite a lot before I ask it here, all answers I got were "buffer in C++ will not be flushed automatically unless a specific statement like std::flush or std::endl is specified. However, I found that the buffer is always automatically flushed in my code.

#include <iostream>

using namespace std;
int main(){
    int i;
    cout << "begin...\n";
    for (i = 0; i<1000000000; i++);
    cout << "end" << endl;
    cin.get();
    return 0;
}

What I got is "begin..." and a new line (\n) were shown first. Then after a few seconds, "end" is shown. Does that mean the buffer was flushed after

cout << "begin...\n";

Or is my understanding wrong?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Ching Lam
  • 11
  • 1
  • 2
    You have a `\n` at the end of the "begin" string. couting an `\n` is the same as couting an `endl`. – Jabberwocky Mar 13 '17 at 13:01
  • 2
    @MichaelWalz [this answer](http://stackoverflow.com/a/213977/4117728) says something different. I also always thought that `endl` puts a new line and flushes while `\n` only puts a new line – 463035818_is_not_an_ai Mar 13 '17 at 13:04
  • 3
    related: http://stackoverflow.com/questions/796865/can-i-stop-stdcout-flushing-on-n – NathanOliver Mar 13 '17 at 13:05
  • @NathanOliver but I have tried both contain \n and without, and both of the results were different from what I expected. – Ching Lam Mar 13 '17 at 13:12
  • I think this might be the most related: http://stackoverflow.com/questions/42430701/does-new-line-character-also-flush-the-buffer – NathanOliver Mar 13 '17 at 13:13
  • @MichaelWalz is it? but I got the same result even if I remove the \n, also isn't \n and endl different when we talking about buffer? – Ching Lam Mar 13 '17 at 13:14
  • The dupe is almost the same question. And answer is what i guessed, but wasnt sure: The implementation may flush the stream whenever it likes. – 463035818_is_not_an_ai Mar 13 '17 at 13:15
  • If I didn't misunderstand, "buffer can (most likely) be automatically flushed anytime in a normal computer", is it? – Ching Lam Mar 13 '17 at 13:17
  • Oh, I got it, but I am now curious about why there isn't a formal/clear explanation of the buffer flushing, anyway, thanks all of youXD – Ching Lam Mar 13 '17 at 13:22

0 Answers0