I've been learning how flushing works with cout, so I decided to perform this quick test.
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
cout << "Line 1..."; // OR cout << "Line 1..." << flush;
usleep(500000);
cout << "\nLine 2" << endl;
cout << "Line 3" << endl ;
return 0;
}
In the case that is presented above, the expected output is for:
Line 1...
Line 2
Line 3
to print out altogether after some delay. However, in the scenario in which
"<< flush;"
is included, the expected result is for Line 1 to print immediately, then after some delay, Line 2 and Line 3 print.
These expected outputs ONLY occur when I compile my program on a Linux machine using the command:
g++ -o myFile.out myFile.cpp -Wall
Then run it using:
./myFile.out
When I run these same code pieces on my windows machine, line 1 is ALWAYS displayed immediately, regardless of the insertion of "<< flush;"
. Why does this happen?
It should be noted that on my windows machine, I am compiling and running my code through codeblocks x64. According to Codeblocks Settings > Compiler > Toolchain Executables, my C++ compiler is "mingw32-g++.exe". Isn't this the same compiler as running g++
on Linux as I did earlier? Thanks!