C++ Ostream::flush() function



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.

Syntax

Following is the syntax for std::ostream::flush() function.

ostream& flush();

Parameters

It does not accepts any parameter.

Return Value

It returns the ostream object (*this).

Exceptions

If an exception is thrown, the object is in a valid state.

Data races

Modifies the stream object.

Example

In 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 −

Hi

Example

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 −

CDEFG

Example

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
Advertisements