2

I understand from here that if i were to output characters without flushing the buffer ( with endl or cin ) they wouldn't appear on my console until the program ends.

So i tried to make an infinite loop:

for(;;)
{
    std::cout << "a" << std::endl;
}

and the same without flushing the buffer:

for(;;)
{
    std::cout << "a";
}

They both output forever a, the only difference i can observe is that the latter version of code has some delay time before it starts outputting the letter. The first one starts immediately.

I was expecting the second one to output the chars only if there was a break in the loop, and the program would be terminated.

Community
  • 1
  • 1
Cătălina Sîrbu
  • 1,253
  • 9
  • 30

1 Answers1

4

You are correct that std::endl, or the use of std::cin, causes a flush to occur, and the contents to be immediately output. std::endl is the equivalent of std::cout.put('\n'); std::cout.flush();, where as std::cin and std::cerr are tie()d to std::cout and therefore any operation to either of those executes std::cout.flush() for you.

However, in the second case, std::cout still has an underlying output sequence (an std::streambuf), which is a specified size. Once this buffer is full, the stream is flushed automatically, and you get the output to the console. Filling up this buffer is what you are seeing with the delay time you mentioned.

ChrisMM
  • 8,448
  • 13
  • 29
  • 48