交换字符串流以输出cout [英] Swapping a stringstream for cout

查看:52
本文介绍了交换字符串流以输出cout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用glibc的stdio,我可以将内存流交换为stdout,从而捕获编译为输出到stdout的一段代码的输出:

With glibc's stdio, I can swap a memstream for stdout, thereby capturing the output of a piece of code compiled to output to 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是否可能. 我天真的尝试不会编译:

I'm curious if the same is possible for iostreams. My naive attempt won't compile:

#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;
}

推荐答案

可以,但不要交换整个流,而只是交换流缓冲区.

You can, but you don't swap the whole stream--just the stream buffer.

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.

Note that in this case, we're not really using the stringstream itself at all, just the stringbuf it contains. If we wanted, we could just define a basic_stringbuf<char> and use that directly instead of defining a stringstream and then only use the stringbuf it contains.

这篇关于交换字符串流以输出cout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆