how can I capture data which will be sent to the stdout in c++?
I found here:
// This can be an ofstream as well or any other ostream
std::stringstream buffer;
// Save cout's buffer 开发者_Python百科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();
And this doesn't work. 'Hello' still outputs before 'STD data:', and buffer.get()
returns '-1'. What's wrong?
Write:
std::cout << buffer.str(); //not buffer.get();
Now its working : http://ideone.com/W8mW8
By the way, std::stringstream::get()
returns std::istream
. See this :
http://www.cplusplus.com/reference/iostream/istream/get/
Recall that std::stringstream
derives from std::istream
. So don't get confused. :-)
精彩评论