使用C ++从控制台应用程序收集stdout输出

使用C ++从控制台应用程序收集stdout输出

问题描述:

我有一个用C ++编写的控制台应用程序。有没有办法收集所有 stdout 输出到字符串/管道/内存数组?

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。我需要在控制台应用程序内,我需要从 stdout 收集。

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.

是的。要将其重定向到字符串,可以使用 std :: stringstream

Yes. To redirect it to a string, you can use a std::stringstream

std::stringstream buffer;
std::streambuf * old = std::cout.rdbuf(buffer.rdbuf());

然后,如果你这样做:

std::cout << "Example output" << std::endl;
std::string text = buffer.str();

您将看到 text code>输出示例\\\

You will see that text now contains "Example output\n".