In C++, output is usually buffered: text collects in memory and is sent to the screen or file later, in one go. flush() forces that to happen now.
It comes in two forms: the member function cout.flush() and the manipulator cout << std::flush. Both do the same job and neither adds a new line. Include <iostream> to use them.
This is a member function of std::ostream. You call it with a dot on a stream object, for example std::cin, std::cout, a file stream, or a std::stringstream. A stream is simply C++'s way to read or write data one piece after another.
Syntax
Use the member function, or put the std::flush manipulator into the stream.
C++
std::cout.flush(); // member function
std::cout << "Loading" << std::flush; // manipulator form
Call
What it does
std::cout.flush()
Sends all waiting output to the screen.
std::cout << std::flush
Same job, written inside an output chain.
std::cout << std::endl
Writes a new line and then flushes. Use ' ' when you do not need the flush.
endl is a new line plus a flush. flush alone adds no new line.
std::cout << "A" writes into the buffer, and std::cout.flush() pushes it out at once.
The same happens with B. Because no new line was written between them, they appear side by side.
The final '\n' moves to the next line. It is not flushed by itself, but the program exit flushes everything.
Example 3 — Flush a File Before Reading It
Write to a file and flush, then read the file with a second stream while the first one is still open. The temporary file flush_demo.txt is created in the current folder.
out << "saved\n" puts the text in the file stream buffer, not yet in the file.
out.flush() writes the buffer to the file, even though out is still open.
The second stream in can now read the line. Without the flush, the file might still be empty at that moment.
Frequently Asked Questions
It sends all buffered output of a stream to its destination, such as the screen or a file, right away.
endl writes a new line and then flushes. flush only flushes. If you need only a new line, write '\n', which is faster.
Yes, at the end of the program, when the buffer is full, when you read from the tied cin, or when you write endl. You flush by hand when you need output to appear earlier.
There is no difference in effect. One is a member call and the other is a manipulator inside a stream chain.
Yes. close() and the destructor of a file stream flush the buffer. flush() is for when you must save the data while the file stays open.