Max Frai
Max Frai

Reputation: 64276

How can I capture data which will be sent to stdout in c++?

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 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?

Upvotes: 3

Views: 1935

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361472

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. :-)

Upvotes: 3

Related Questions