C++ IOS::set_rdbuf() function



The C++ std::ios::set_rdbuf() function is used to set a new stream buffer for an input/output stream object. It allows redirection of the I/O operations to a different buffer, enabling the custom handling of I/O operations.

Syntax

Following is the syntax for std::ios::set_rdbuf() function.

void set_rdbuf (streambuf* sb);

Parameters

  • sb − It indicates the pointer to a streambuf object(This shall not be a null pointer).

Return Value

This function does not return anything

Exceptions

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

Data races

Modifies the stream object.

Concurrent access to the same stream object may cause data races.

Example

Let's look at the following example, where we are going to redirect std::cout to std::ostringstream.

#include <iostream>
#include <sstream>
int main()
{
    std::ostringstream x;
    std::streambuf* a = std::cout.rdbuf(x.rdbuf());
    std::cout << "Welcome To, TutorialsPoint." << std::endl;
    std::cout.rdbuf(a);
    std::cout << " " << x.str() << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Welcome To, TutorialsPoint.

Example

Consider the following example, where we are going to redirect std::cin to a std::istringstream.

#include <iostream>
#include <sstream>
int main()
{
    std::istringstream x("1 2.12 POLO");
    std::streambuf* y = std::cin.rdbuf(x.rdbuf());
    int a;
    double b;
    std::string c;
    std::cin >> a >> b >> c;
    std::cin.rdbuf(y);
    std::cout << " " << a << ", " << b << ", " << c << std::endl;
    return 0;
}

Output

Following is the output of the above code −

1, 2.12, POLO
ios.htm