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

pyC*_*hon 12 c++ c++11

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

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

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

我不是想通过终端这样做的方法

Naw*_*waz 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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

<redirected-output>
hello world
Hello from print_to_console()
</redirected-output>
Run Code Online (Sandbox Code Playgroud)

参见在线演示.

  • *但我认为你不应该使用auto ptr*:p (5认同)
  • 如果他们使用printf,put,write等会发生什么? (4认同)
  • 哇,我完全忘了你能做到这一点. (2认同)
  • `auto*old_buf`?是否需要指针?auto不会丢弃指针. (2认同)

Naw*_*waz 7

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

如果他们使用printf,put,write等会发生什么? - 安德烈·科斯特尔

因为printf,我提出了以下解决方案.它仅适用于POSIX,因为fmemopen仅适用于POSIX,但如果您愿意,可以使用临时文件 - 如果您想要便携式解决方案,那将会更好.基本想法是一样的.

#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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

<redirected-output>
hello world
Hello from print_to_console()
</redirected-output>
Run Code Online (Sandbox Code Playgroud)

在线演示.