c++ - 将 stringstream 换成 cout

标签 c++ iostream

使用 glibc 的 stdio,我可以将 memstream 换成 std​​out,从而捕获一段编译后的代码输出到 stdout:

#include <stdio.h>

void swapfiles(FILE* f0, FILE* f1){ FILE tmp; tmp = *f0; *f0 = *f1; *f1 = tmp; }

void hw_c(){ puts("hello c world"); }

int c_capt(){
  FILE* my_memstream;
  char* buf  = NULL;
  size_t bufsiz = 0;

  if( (my_memstream = open_memstream(&buf, &bufsiz)) == NULL) return 1;

  FILE * oldstdout = stdout;

  swapfiles(stdout, my_memstream);
  hw_c();
  swapfiles(stdout, my_memstream);

  fclose(my_memstream);
  printf("Captured: %s\n", buf);
}

我很好奇 iostreams 是否也可以这样做。 我天真的尝试不会编译:

#include <iostream>
#include <string>
#include <sstream>

void hw_cc(){ std::cout<<"hello c++ world\n"; }
int cc_capt(){
  using namespace std;

  stringstream ss;
  string capt;

  //std::swap(ss,cout); //<- the compiler doesn't like this
  hw_cc();
  //std::swap(ss,cout); 

  cout<<"Captured: "<<capt<<'\n';
}

int main(int argc, char** argv){
  c_capt();
  puts("---------------------------------");
  cc_capt();
  return 0;
}

最佳答案

你可以,但你不会交换整个流——只是流缓冲区。

void cc_capt() {
    using namespace std;

    stringstream ss;

    auto orig = std::cout.rdbuf(ss.rdbuf());

    hw_cc();

    std::cout.rdbuf(orig);

    std::cout << "captured: " << ss.str() << "\n";
}

请注意,在这种情况下,我们并没有真正使用 stringstream本身,只是stringbuf它包含。如果我们愿意,我们可以定义一个 basic_stringbuf<char>并直接使用它而不是定义 stringstream然后只使用 stringbuf它包含。

关于c++ - 将 stringstream 换成 cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37758378/

相关文章:

c++ - 实验性::文件系统链接器错误

c++ - 如何让好友功能有内部链接

c++ - 派生 basic_ostream : "using" keyword and ambiguous overload for operator <<

c++ - 从类模板继承所需的 iostream

c++ - 双印不失精度

c++ - iostream.h 中用于 conio.h 的 getch() 的替代函数?

c++ - C2440返回无法从 'string'转换为 'string *'

C++ 是否需要重载运算符的特殊右值变体?

c++ - Define and deduce the parameter from Template 模板参数

c++ - 在 C++ 中打印变量名的通用方法