Q:
there has been many previous questions about redirecting stdout/stderr to a file. is there a way to redirect stdout/stderr to a string?
A:
Yes, you can redirect it to an std::stringstream:
std::stringstream buffer;
std::streambuf * old = std::cout.rdbuf(buffer.rdbuf());
std::cout << "Bla" << std::endl;
std::string text = buffer.str(); // text will now contain "Bla\n" You can use a simple guard class to make sure the buffer is always reset:
struct cout_redirect {
cout_redirect( std::streambuf * new_buffer )
: old( std::cout.rdbuf( new_buffer ) )
{ }
~cout_redirect( ) {
std::cout.rdbuf( old );
}
private:
std::streambuf * old;
};
本文介绍了一种将C++程序中的标准输出(stdout)和标准错误输出(stderr)重定向到字符串的方法,并提供了一个简单的保护类确保缓冲区始终被重置。

1014

被折叠的 条评论
为什么被折叠?



