问题
I have a console application written with C++. Is there any way to collect all stdout output from it to string/pipe/memory array?
PS. I need to do this from within the console app that I'm needing to collect stdout from. Or, in other words, it is collecting from itself.
回答1:
Yes. To redirect it to a string, you can use a std::stringstream
std::stringstream buffer;
std::streambuf * old = std::cout.rdbuf(buffer.rdbuf());
Then, if you do:
std::cout << "Example output" << std::endl;
std::string text = buffer.str();
You will see that text now contains "Example output\n".
来源:https://stackoverflow.com/questions/15419523/collect-stdout-output-from-a-console-app-with-c