In C++, unitbuf turns on unit buffering: after every output operation the stream flushes its buffer at once. Text then reaches the screen or file without waiting.
The standard error stream std::cerr already works this way, so error messages show up immediately. You can switch the same behaviour on for cout or a file stream. It comes from <ios>, which <iostream> includes.
This is a manipulator. You do not call it on its own. You send it into a stream with << or >>, and it changes how that stream behaves from then on (or does one small job, like ending a line).
Syntax
Put std::unitbuf into an output stream.
C++
std::cout << std::unitbuf; // flush after every <<
out << std::unitbuf << "text\n";
Call
What it does
std::cout << std::unitbuf
Turns on flush after every output.
std::cout.flags() & std::ios::unitbuf
Non-zero when the flag is on.
std::cout << std::nounitbuf
Turns the behaviour off again.
Flushing after every output is slow for large amounts of text. Use unitbuf for logs and progress messages, not for bulk output.
Library declarations
C++
ios_base& unitbuf(ios_base& str);
Parameters
Parameter
Description
str
The stream. It is passed in for you when you write cout << unitbuf. You never write this argument yourself.
Return Value
Return Value
Description
ios_base&
A reference to the same stream, so you can keep chaining << or >> after unitbuf.
C++ Examples
Example 1 — See Which Streams Use unitbuf
Ask each stream whether the flag is on. cerr has it from the start.