如何捕获将在c ++中发送到stdout的数据?
我在这里找到了:
// This can be an ofstream as well or any other ostream
std::stringstream buffer;
// Save cout's buffer here
std::streambuf *sbuf = std::cout.rdbuf();
// Redirect cout to our stringstream buffer or any other ostream
std::cout.rdbuf(buffer.rdbuf());
std::cout << "Hello!";
// When done redirect cout to its old self
std::cout.rdbuf(sbuf);
std::cout << "STD data: \n";
std::cout << buffer.get();
这不起作用。 'Hello'仍然在'STD data:'之前输出,buffer.get()
返回'-1'。怎么了?
答案 0 :(得分:3)
写:
std::cout << buffer.str(); //not buffer.get();
现在正在工作:http://ideone.com/W8mW8
顺便说一下,std::stringstream::get()
会返回std::istream
。见:
http://www.cplusplus.com/reference/iostream/istream/get/
回想一下,std::stringstream
来自std::istream
。所以不要混淆。 : - )