重定向输出一个函数打印到控制台到字符串 [英] redirect output of an function printing to console to string

查看:468
本文介绍了重定向输出一个函数打印到控制台到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说,我们有一个函数,它打印文本到控制台,我们不能控制源,但我们能够调用它。例如

lets say we have a function which prints text to the console and in which we do not have control over the source but we are able to call it. For example

void foo() {
    std::cout<<"hello world"<<std::endl; 
    print_to_console(); // this could be printed from anything
}

上面的函数到一个字符串,而不改变函数本身?

is it possible to redirect the output of the above function to a string without changing the function itself?

我不是在寻找一个办法通过终端

I'm not looking for a way to do this via terminal

推荐答案

是的。这可以做到。下面是一个小演示:

Yes. That can be done. Here is a little demo:

#include <sstream>
#include <iostream>

void print_to_console() {
    std::cout << "Hello from print_to_console()" << std::endl;
}

void foo(){
  std::cout<<"hello world"<<std::endl; 
  print_to_console(); // this could be printed from anything
}
int main()
{
    std::stringstream ss;

    //change the underlying buffer and save the old buffer
    auto old_buf = std::cout.rdbuf(ss.rdbuf()); 

    foo(); //all the std::cout goes to ss

    std::cout.rdbuf(old_buf); //reset

    std::cout << "<redirected-output>\n" 
              << ss.str() 
              << "</redirected-output>" << std::endl;
}

输出:

<redirected-output>
hello world
Hello from print_to_console()
</redirected-output>

查看在线演示

这篇关于重定向输出一个函数打印到控制台到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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