I think the problem is output buffering.
In C ++, input and output streams can be in one of three states: unbuffered (any output immediately goes to the target file / pipe / console), buffered line by line (characters get to the output after the end of each line, exhausting the internal buffer or closing the stream), and is fully buffered (characters enter the output only after the internal buffer is exhausted or the stream is closed).
The Microsoft implementation of the standard library never does line-by-line buffering (read the answer from Stephan T. Lavavej ), implementation on Linux is usually done.
This answer contains a quote from the standard (C11 7.21.3 §7):
It can be determined that it can be determined by the user.
(this refers to pure C). C ++ has the same policy, according to this answer :
C ++ 11 27.4.2 [narrow.stream.objects] / 3 : This is where the object stream is associated with the object stdout .
This means that if the output is made to the console, and not to a file, then you will always see the full line after \n . But if the output is redirected, then buffering will occur.
Here is an example. Consider the code:
#include "stdafx.h" #include <iostream> #include <chrono> #include <thread> int main() { std::cout.sync_with_stdio(false); std::cout << "this is " << "\n"; std::this_thread::sleep_for(std::chrono::seconds(10)); std::cout << "SPARTAAAA!!!111" << std::endl; return 0; }
in MSVC 2015. If we start the program in an ordinary way, we will see this is first, and only after 10 seconds SPARTA . And if you start the program like this: a.exe >x.txt , and look a few seconds after launching it into the x.txt file, then you will not see anything there until the end of the program.
If you replace "\n" with std::endl , output to a file works the same way as to the console.
Update: in MSVC 2015, std::cout can be manually buffered (the idea is gratefully stolen by a peep in this answer ):
std::cout.sync_with_stdio(false); char mybuf[1024]; std::cout.rdbuf()->pubsetbuf(mybuf, 1024); std::cout << "this is " << "\n"; std::this_thread::sleep_for(std::chrono::seconds(10)); std::cout << "SPARTAAAA!!!111" << std::endl; return 0;
This code only displays text after std::endl .