将函数打印的输出重定向到控制台到字符串

时间:2013-10-21 02:52:53

标签: c++ c++11

假设我们有一个函数可以将文本打印到控制台,我们无法控制源,但我们可以调用它。例如

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

是否可以将上述函数的输出重定向到字符串而不更改函数本身?

我不是想通过终端

来做到这一点

3 个答案:

答案 0 :(得分:26)

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

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

请参阅Online Demo

答案 1 :(得分:7)

@Andre在我的第一个回答的评论中问道:

  

如果他们使用printf,puts,write等会怎么样? - 安德烈·科斯图尔

对于printf,我提出了以下解决方案。它仅适用于POSIX,因为fmemopen仅适用于POSIX,但如果您愿意,可以使用临时文件 - 如果您想要 portable <会更好/ em>解决方案。基本思路是一样的。

#include <cstdio>

void print_to_console() {
    std::printf( "Hello from print_to_console()\n" );
}

void foo(){
  std::printf("hello world\n");
  print_to_console(); // this could be printed from anything
}

int main()
{
    char buffer[1024];
    auto fp = fmemopen(buffer, 1024, "w");
    if ( !fp ) { std::printf("error"); return 0; }

    auto old = stdout;
    stdout = fp;

    foo(); //all the std::printf goes to buffer (using fp);

    std::fclose(fp);
    stdout = old; //reset

    std::printf("<redirected-output>\n%s</redirected-output>", buffer);
}

输出:

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

Online Demo

答案 2 :(得分:1)

class buffer
    : public std::streambuf
{
public:
    buffer(std::ostream& os)
        : stream(os), buf(os.rdbuf())
    { }

    ~buffer()
     {
         stream.rdbuf(buf);
     }

private:
    std::ostream& stream;
    std::streambuf* buf;
};

int main()
{
    buffer buf(std::cout);
    std::stringbuf sbuf;

    std::cout.rdbuf(sbuf);

    std::cout << "Hello, World\n";
}