c++ - std::cout、ostream等获取输出流

标签 c++ std iostream

在我的项目(虚幻引擎 4)中,我没有输出流 - 相反,我可以通过 UE_LOG 函数进行通信,该函数的工作方式与 printf() 非常相似。问题是我刚刚创建了一个 .dll 库(不包含 Unreal),我想通过 iostream 进行通信。我的想法是 - 在 .dll 库中,我使用标准 cout 将消息写入 ostream,我在虚幻引擎函数中使用所有这些,在其中我以字符串形式获取 ostream并将其输出到UE_LOG函数中。

问题是我总是将 std::cout 视为魔法的一部分,而不去思考里面到底是什么(我很确定我们大多数人都这么做了)。我该如何处理这个问题?简单的方法是行不通的(比如抓取 stringstream 并将其输出到 UE_LOG)。

最佳答案

My idea is - inside .dll library I use standard cout to write messages into ostream

您实际上可以用您自己的实现替换 std::cout 使用的输出缓冲区。使用std::ostream::rdbuf()函数来执行此操作(引用文档中的示例):

#include <iostream>
#include <sstream>

int main()
{
    std::ostringstream local;
    auto cout_buff = std::cout.rdbuf(); // save pointer to std::cout buffer

    std::cout.rdbuf(local.rdbuf()); // substitute internal std::cout buffer with
        // buffer of 'local' object

    // now std::cout work with 'local' buffer
    // you don't see this message
    std::cout << "some message";

    // go back to old buffer
    std::cout.rdbuf(cout_buff);

    // you will see this message
    std::cout << "back to default buffer\n";

    // print 'local' content
    std::cout << "local content: " << local.str() << "\n";
}

关于c++ - std::cout、ostream等获取输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39434944/

相关文章:

c++ - 图像处理中的并发设计

c++ - 如何打印(使用 cout)二进制形式的数字?

java - 为什么这里出现 "too many open file"错误

c++ - C++ 中 vector 的 .size() 到底做了什么?

c++ - 对可变参数模板和模板类型推导的误解

c++ - 如何在没有范围的情况下使用枚举类

c++ - STL 迭代器循环

c++ -::std::mutex 在 std 之前使用时是什么意思

c++ - 清除已经为空的 vector 会导致未定义的行为吗?

c++ - 为什么 iostream::eof 在循环条件(即 `while (!stream.eof())` )内被认为是错误的?