简体   繁体   English

C ++捕获输出流

[英]C++ catch output stream

I have a c++ library that provides an object with complicated logic. 我有一个c ++库,可为对象提供复杂的逻辑。 So far, many objects print their output to std::cout when one single library command is executed. 到目前为止,执行一个库命令时,许多对象会将其输出打印到std::cout I want to create a Qt GUI for this (output it in a text widget instead of console output), so std::cout has to be changed for something more flexible. 我想为此创建一个Qt GUI(在文本窗口小部件中输出而不是在控制台输出中),因此必须更改std::cout以获得更灵活的功能。 I have passed a reference to std::stringstream parameter to the main object (and it passes it down to lower objects) and replaced all "std::cout << " with "stream << " (stream is std::stringstream). 我已经将对std::stringstream参数的引用传递给了主要对象(并将其传递给较低的对象),并将所有“ std :: cout <<”替换为“ stream <<”(流是std :: stringstream) 。

It doesn't work, because I lose most of the output. 它不起作用,因为我丢失了大部分输出。 When I want to fetch it from the stringstream, it's ridiculously small (just few characters). 当我想从字符串流中获取它时,它太小了(只有几个字符)。 It seems that if I do stream << var1 << var2 << var3 only var3 will be available. 看来,如果我执行stream << var1 << var2 << var3只有var3可用。

Don't know how to solve this problem. 不知道如何解决这个问题。 If I passed a reference to std::cout as the main object parameter, everything would be ok under console, but it'd not work for the GUI application (I guess I cannot fetch output from std::cout). 如果我将对std::cout的引用作为主要对象参数传递,则在控制台下一切正常,但不适用于GUI应用程序(我想我无法从std :: cout获取输出)。

Please tell me if I'm using streamstring in a bad way. 请告诉我是否以不好的方式使用了流字符串。 Or let me know if there is a better way to fetch the output (use something else instead of stringstream). 或者让我知道是否有更好的方法来获取输出(使用其他方法代替stringstream)。 Many thanks in advance. 提前谢谢了。

you could use freopen("out.txt","w",stdout); 您可以使用freopen(“ out.txt”,“ w”,stdout); at the start of your program. 在程序开始时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM