c++ - 监视标准输出缓冲区并重定向到字符串 C++

标签 c++ stdout io-redirection

我有多个正在打印的 .cpp 文件,我想将其重定向到一个字符串。我的项目结构是:一个主文件,它调用另一个文件和另一个文件的函数。如果我有一个 .cpp 文件,使用 stringstream 很容易,但如果有多个文件,我该如何解决?

主要.cpp:

#include "Second.h"

int main() {
    std::string buffer = "First line";
    printOut(buffer);
    std::cout << "Hello world" << std::endl;
}

第二个.h:

#include <string>

void printOut(std::string buffer);

第二个.cpp

#include "Second.h"

void printOut(std::string buffer) {
    std::cout << buffer << std::endl;
}

在这种情况下,字符串应如下所示:

redirectedString = First line\nHello World\n

最佳答案

可以使用合适的流缓冲区拦截标准流的输出。例如:

void do_something_with(std::string const& s) {
    // ...
 }

struct basicbuf: std::streambuf {
    std::string buf;
    int_type overflow(int_type c) {
        if (c != traits_type::eof()) {
             this->buf.push_back(c);
        }
        return traits_type::not_eof(c);
    }
    int sync() {
         do_something_with(buf);
         buf.clear();
         return 0;
    }
};

int main() {
     basicbuf buf;
     std::streambuf* orig = std::cout.rdbuf(&buf);

     std::cout << "hello, world\n" << std::flush;
     std::cout.rdbuf(orig);
}

当使用多线程时,您可能希望使用线程本地缓冲区来避免数据竞争。被调用的函数会主动将缓冲区转移到需要的地方。

关于c++ - 监视标准输出缓冲区并重定向到字符串 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41301030/

相关文章:

c++ - CPPRest SDK 向服务器发出 HTTP 请求

cocoa - 运行 a 命令时将 `stdout` 放入 `NSTextView` 中

php - 使用 PHP 从 C 应用程序的 STDOUT 读取数据

ruby 脚本 : parent output missing after exec

linux - 在两个脚本之间使用 I/O 重定向,无需等待第一个脚本完成

c++ - 在集合中查找重复元素并将其分组的快速算法是什么?

c++ - 如何按类型(不是值)添加使用指向成员值的指针作为模板参数

c++ - 使用 CDC 的 MFC 打印仅适用于某些打印机

debugging - 当 "codec => rubydebug"时,logstash 在哪里写入日志?

java - 输入重定向到键盘输入