Home > Backend Development > C++ > How to Capture Standard Output and Error Streams in a String in C ?

How to Capture Standard Output and Error Streams in a String in C ?

Patricia Arquette
Release: 2024-11-04 01:24:30
Original
327 people have browsed it

How to Capture Standard Output and Error Streams in a String in C  ?

How to Redirect Output to a String in C

For various debugging and testing scenarios, it can be convenient to redirect the standard output and error streams to a string rather than to the console.

Solution: Using std::stringstream

To redirect stdout/stderr to a string, you can utilize the std::stringstream class:

<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 will now contain "Bla\n"</code>
Copy after login

Guard Class for Buffer Reset

To ensure that the buffer is reset after redirecting, you can create 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>
Copy after login

This guard class guarantees that the buffer is always restored to its original state, even in the event of exceptions.

The above is the detailed content of How to Capture Standard Output and Error Streams in a String in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template