Home > Enterprise >  How to store cout in string and then output the string to console?
How to store cout in string and then output the string to console?

Time:11-01

I am trying to store the output of my program in a file, and even though I know there are various much simpler methods, I want to solve the problem using strings since I would like to know the logic behind it.

So far, I understand the implementation:

std:: stringstream s;
s << "string";

and I know at some point I will have the following code

cout << s.str()

but how do I store my program output in the string stream without providing the string itself? Put another way, how do I redirect the cout statements within my program to a string?

CodePudding user response:

If your goal is to redirect std::cout to a std::string, you can use the cout.rdbuf() method to give std::cout a different buffer to write to, such as the buffer of a std::ostringstream (or a std::ofstream, etc).

The above linked documentation provides the following example of exactly this:

#include <iostream>
#include <sstream>

int main() {
    std::ostringstream local;
    auto cout_buff = std::cout.rdbuf(); // save pointer to std::cout buffer

    std::cout.rdbuf(local.rdbuf()); // substitute internal std::cout buffer with
        // buffer of 'local' object

    // now std::cout work with 'local' buffer
    // you don't see this message
    std::cout << "some message";

    // go back to old buffer
    std::cout.rdbuf(cout_buff);

    // you will see this message
    std::cout << "back to default buffer\n";

    // print 'local' content
    std::cout << "local content: " << local.str() << "\n";
}
  • Related