如何捕获将在c ++中发送到stdout的数据?

时间:2011-04-16 14:52:38

标签: c++ stream stdout

如何捕获将在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'。怎么了?

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。所以不要混淆。 : - )