重定向标准输出/标准错误将一个字符串 [英] redirect stdout/stderr to a string
本文介绍了重定向标准输出/标准错误将一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一直存在有关重定向标准输出/标准错误到一个文件中许多previous问题。有没有一种方法,标准输出/标准错误重定向到一个字符串?
there has been many previous questions about redirecting stdout/stderr to a file. is there a way to redirect stdout/stderr to a string?
推荐答案
是的,您可以将其重定向到一个的std :: stringstream的
:
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;
};
这篇关于重定向标准输出/标准错误将一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文