Home >Backend Development >C++ >How to Redirect stdout/stderr to a String in C ?
Redirecting stdout/stderr to a String in C
While there are numerous discussions on redirecting stdout/stderr to files, it is also possible to redirect these outputs to a string. This article explores how to accomplish this with the help of std::stringstream and a guard class.
Answer:
To redirect stdout/stderr to a string, you can employ std::stringstream. Here's how it works:
<code class="cpp">std::stringstream buffer; std::streambuf * old = std::cout.rdbuf(buffer.rdbuf()); std::cout << "Bla" << std::endl; std::string text = buffer.str(); // text now contains "Bla\n"</code>
This method captures the console output into a string.
To ensure proper cleanup, you can utilize a guard class:
<code class="cpp">struct cout_redirect { cout_redirect( std::streambuf * new_buffer ) : old( std::cout.rdbuf( new_buffer ) ) { } ~cout_redirect( ) { std::cout.rdbuf( old ); } private: std::streambuf * old; };</code>
By using this guard, you can rest assured that the buffer is always reset, ensuring proper console I/O handling.
The above is the detailed content of How to Redirect stdout/stderr to a String in C ?. For more information, please follow other related articles on the PHP Chinese website!