In general, std::cout is not buffered by default: as long as sync_with_stdio is active, every byte written to std::cout's buffer is immediately pushed to stdout's buffer.
stdout is line-buffered by default in POSIX, so if you run the above program using gcc on linux (with C++ sleep instead of Windows Sleep), you will not observe the output until after the pause.
Based on "Sleep(5000);" however, this is using Windows. There, C I/O streams are not buffered (at least not in VS 2013 I have on this computer) You can observe that by replacing std::cout << "test"; with printf("test");. The output still appears immediately.
You can still make Windows delay the output, if you enable buffering on stdout:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
#include <cstdio>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
int main()
{
char buf[BUFSIZ];
std::setbuf(stdout, buf);
std::cout << "test";
// std::fflush(stdout); // <- uncomment to see the text before the pause
Sleep(5000);
std::fflush(stdout);
std::setbuf(stdout, NULL); // don't let the stream outlive the buffer
}
|
Actually, that demo won't let you observe the effect of
std::flush
, since flush only moves cout's buffer (which it doesn't even have by default) into stdout's buffer, where the output sits until flushed using
std::fflush
or implicit means.
To obseve
std::flush
, give std::cout its own buffer and disconnect it from C I/O streams:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
int main()
{
char buf[BUFSIZ];
std::ios::sync_with_stdio(false);
std::cout.rdbuf()->pubsetbuf(buf, sizeof buf);
std::cout << "test";
//std::cout << std::flush; // <- uncomment to obseve the output before the pause
Sleep(5000);
std::cout << std::flush;
std::cout.rdbuf()->pubsetbuf(nullptr, 0); // don't let the stream outlive the buffer
}
|