Redirecting Stdout/Stderr to a String
While redirecting stdout/stderr to a file is a common practice, there are scenarios where capturing the output as a string is more suitable. In this article, we will explore how to achieve this using standard C libraries.
Using Stringstream
One approach is to leverage the std::stringstream class. By redirecting stdout/stderr to a stringstream object, you can capture the output as a string. Here's an example:
1 2 3 4 5 6 |
|
This code first creates a stringstream and assigns its buffer to cout. Any subsequent output to cout will be captured by the stringstream. After the redirection is complete, you can access the captured text using the str() method of the stringstream.
Using a Guard Class
To ensure that the buffer is always properly reset, you can create a guard class. Here's an example:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
The cout_redirect class allows you to temporarily redirect stdout/stderr within its scope. When an object of this class is created, the old buffer is stored. Upon its destruction, the old buffer is restored.
By utilizing these techniques, you can easily capture the output of stdout/stderr as a string, providing flexibility in managing output within your C applications.
The above is the detailed content of How to Capture Stdout/Stderr Output as a String in C ?. For more information, please follow other related articles on the PHP Chinese website!