我该如何在C++中捕获将要发送到标准输出的数据?
我在这里找到了相关信息:
// 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();
但这并不起作用。在“STD数据:”之前仍然输出“Hello”,而buffer.get()
返回“-1”。出了什么问题?