The C++ std::ostream::flush() function is used to clear the output buffer of an output stream, ensuring that all the data is written to the intended destination immediately. This function can be invoked using the flush manipulator, like std::cout <<std::flush;.
Flushing can also automatically when the stream is closed, when the buffer is full, or at specific points defined by the system.
SyntaxFollowing is the syntax for std::ostream::flush() function.
ostream& flush();Parameters
It does not accepts any parameter.
Return ValueIt returns the ostream object (*this).
ExceptionsIf an exception is thrown, the object is in a valid state.
Data racesModifies the stream object.
ExampleIn the following example, we are going to consider the basic usage of the flush() function.
#include <iostream> int main() { std::cout << "Hi" << std::flush; return 0; }Output
Output of the above code is as follows −
HiExample
Consider the following example, where we are going to perform flushing after each character.
#include <iostream> int main() { for (char x = 'C'; x <= 'G'; ++x) { std::cout << x << std::flush; } return 0; }Output
Following is the output of the above code −
CDEFGExample
Let's look at the following example, where std::cout is flushed after the prompt "Enter your name:".
#include <iostream> int main() { std::cout << "Enter Name : " << std::flush; std::string a; std::cin >> a; std::cout << "Welcome, " << a << std::endl; return 0; }Output
If we run the above code it will generate the following output −
Enter Name : Mr.X Welcome, Mr.X
ostream.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4