将std :: cout重定向到自定义编写器 [英] redirect std::cout to a custom writer

查看:298
本文介绍了将std :: cout重定向到自定义编写器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Mr-Edd的iostreams文章中的这段程式码print std :: clog某处。

I want to use this snippet from Mr-Edd's iostreams article to print std::clog somewhere.

#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>

int main()
{
    std::ostringstream oss;

    // Make clog use the buffer from oss
    std::streambuf *former_buff =
        std::clog.rdbuf(oss.rdbuf());

    std::clog << "This will appear in oss!" << std::flush;

    std::cout << oss.str() << '\\n';

    // Give clog back its previous buffer
    std::clog.rdbuf(former_buff);

    return 0;
}

因此,在mainloop中,我会做一些

so, in a mainloop, I will do something like

while (! oss.eof())
{
    //add to window text somewhere
}

这是 ostringstream docs 但我无法理解最好的方法做到这一点。我有一个方法显示文本,我只想调用它与任何数据在ostringstream。

Here's the ostringstream docs but I'm having trouble understanding the best way to do this. I have a method that displays the text, I just want to call it with any data in the ostringstream.

什么是最简单的/最好的方式发送到std :: clog重定向到我选择的方法?它是如上所述,并填写while!eof部分(不知道如何),还是有更好的方式,说通过重载一些提交运算符在某处调用我的方法?我很喜欢快速和容易,我真的不想开始定义水槽和boost iostreams像文章那样 - 这些东西是我的头。

What is the easiest/best way to get anything sent to std::clog redirected to a method of my choice? is it as above, and fill in the while !eof part (not sure how), or is there a better way, say by overloading some 'commit' operator somewhere that calls my method? I'm loking for quick and easy, I really don't want to start defining sinks and such with boost iostreams as the article does - that stuff is way over my head.

推荐答案

我鼓励您查看 Boost.IOStreams 。它似乎适合您的使用案例很好,使用它是令人惊讶的简单:

I encourage you to look at Boost.IOStreams. It seems to fit your use-case nicely, and using it is surprisingly simple:

#include <boost/iostreams/concepts.hpp> 
#include <boost/iostreams/stream_buffer.hpp>
#include <iostream>

namespace bio = boost::iostreams;

class MySink : public bio::sink
{
public:
    std::streamsize write(const char* s, std::streamsize n)
    {
        //Do whatever you want with s
        //...
        return n;
    }
};

int main()
{
    bio::stream_buffer<MySink> sb;
    sb.open(MySink());
    std::streambuf * oldbuf = std::clog.rdbuf(&sb);
    std::clog << "hello, world" << std::endl;
    std::clog.rdbuf(oldbuf);
    return 0;
}

这篇关于将std :: cout重定向到自定义编写器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆