以前有很多關(guān)于將stdout / stderr重定向到文件的問題。有沒有一種方法可以將stdout / stderr重定向到字符串?
3 回答

蝴蝶不菲
TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
是的,您可以將其重定向到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"
您可以使用簡(jiǎn)單的防護(hù)類來確保始終重置緩沖區(qū):
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;
};
- 3 回答
- 0 關(guān)注
- 1092 瀏覽
添加回答
舉報(bào)
0/150
提交
取消