2015-11-13 33 views
0

我有一个库提供的功能(所以我不能编辑它的源代码),打印输出到标准输出。我希望得到一个字符串变量的输出,以便我可以检查它的一些条件。做这个的最好方式是什么?我可以在没有多线程和文件I/O的情况下执行此操作吗?如何获得输出发送到标准输出到字符串

[编辑]类似的问题(在评论中指出):

使用多线程:

Capture Output of Spawned Process to string

如果你知道输出大小预先:

redirect output from stdout to a string?

+0

您是试图在程序内部执行此操作,还是只想从终端获取bash脚本? – tonysdg

+0

我的程序内部。 – SPMP

+2

你可以用这样的东西将stdout重定向到一个文件。 http://stackoverflow.com/questions/14543443/in-c-how-do-you-redirect-stdin-stdout-stderr-to-files-when-making-an-execvp-or绝对不是最干净的方式,但它将允许您然后打开文件阅读并比较。应该能够重定向到一个指针,但我无法在任何地方找到它。 – arduic

回答

1

使用rdbuf 。

std::stringstream stream; 
auto * old = std::cout.rdbuf(stream.rdbuf()); 
CallFunction(); 
std::cout.rdbuf(old); 
std::string value = stream.str();