c++ stream buffer and flush

Viewed 226
#include <iostream>
#include <chrono>
#include <thread>

using namespace std::chrono;


int main() {
    std::cout << "hello";
    std::this_thread::sleep_for(2s);
    std::cout << "world"<<std::endl;
}

I m using visual studio 2019.
I expect above code to print helloworld after 2 seconds but hello is displayed before 2 seconds in the console(i.e instantly when i run the program) and world is displayed after 2 seconds.
I read about buffer recently and came to know that the text should be displayed in the console only after the buffer is full. We can force to flush the buffer by using \n, manupulators and cin.

But why am I not seeing desired behavior in this particular example?
Isn't cout using buffer?
Is it flushed for every character?

1 Answers

There is no strict rule in the standard when a buffer should be flushed.

Like @Yksisarvinen mentioned in the comments, a flush isn't affected by the compiler but by the operating system. Also \n doesn't always trigger a flush. If the cout is going to a terminal, it is usually line buffered, thus you can force a flush via \n.

More information can be found at: When does cout flush? and Does new line character also flush the buffer?

Related