[英]std::cout, ostream and other kinds of getting output stream
在我的项目(虚幻引擎4)中,我没有输出流,而是可以通过UE_LOG函数进行通信,该函数的工作原理与printf()
非常相似。 问题是我只是制作了一个.dll库(不包含Unreal包含),我想通过iostream
进行通信。 我的想法是-在.dll库中,我使用标准cout
将消息写入ostream,我在Unreal Engine函数中使用所有消息,在其中我以字符串形式获取ostream
并将其输出到UE_LOG函数中。
问题是我一直把std::cout
当作魔术的一部分,而不考虑里面到底是什么(我敢肯定我们大多数人都做过)。 我该如何处理? 简单的方法不起作用(例如获取stringstream
并将其输出到UE_LOG中)。
我的想法是-在.dll库中,我使用标准cout将消息写入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";
}
(以防我的编辑未被正面评价)
来自OP:感谢您的提示,我终于找到了解决问题的方法。 假设我想从cout获取流并将其发送到printf(因为我认为stdio库优于iostream)。 在这里,我该怎么做:
#include <iostream>
#include <sstream>
#include <cstdio>
using namespace std;
class ssbuf : public stringbuf{
protected:
int sync(){
printf("My buffer: %s",this->str().c_str());
str("");
return this->stringbuf::sync();
}
};
int main(){
ssbuf *buf = new ssbuf();
cout.rdbuf(buf);
cout<<"This is out stream "<<"and you cant do anything about it"<<endl;
cout<<"(don't) "<<"Vote Trump"<<endl;
}
代码是很原始的,但是确实可以。 我使缓冲区的子类具有方法sync()向下转换原始虚拟方法sync()。 除此之外,它的工作方式与通常的缓冲区一样,只是抓住了所有控制台输出流-正是我们想要的。 里面的str(“”)用来清理缓冲区-可能没有输出的流不会清理自身。
非常感谢您的帮助! 大GRIN为您服务! :d
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.