Collect stdout output from a console app with C++

2019-08-28 04:48发布

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条回答
贼婆χ
2楼-- · 2019-08-28 05:27

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".

查看更多
登录 后发表回答