6

我想使用Mr-Edd 的 iostreams 文章中的这个片段在某处打印 std::clog。

#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;
}

所以,在主循环中,我会做类似的事情

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

这是ostringstream 文档,但我无法理解执行此操作的最佳方法。我有一个显示文本的方法,我只想用 ostringstream 中的任何数据调用它。

将发送到 std::clog 的任何内容重定向到我选择的方法的最简单/最佳方法是什么?是如上所述,并填写 while !eof 部分(不确定如何),还是有更好的方法,比如在某处重载一些调用我的方法的“提交”运算符?我正在寻找快速和简单的方法,我真的不想像文章那样开始使用 boost iostreams 定义接收器之类的东西——这些东西太让我头疼了。

4

5 回答 5

11

我鼓励你看看Boost.IOStreams。它似乎很适合您的用例,并且使用起来非常简单:

#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;
}
于 2009-02-10T18:34:11.520 回答
8

认为您想在不为空的情况下从 ostream 中提取文本。你可以这样做:

std::string s = oss.str();
if(!s.empty()) {
    // output s here
    oss.str(""); // set oss to contain the empty string
}

如果这不是你想要的,请告诉我。

当然,更好的解决方案是去掉中间人,让一个新的streambuf去你真正想要的地方,以后不需要再去探查了。像这样的东西(注意,这对每个字符都有效,但在 streambufs 中也有很多缓冲选项):

class outbuf : public std::streambuf {
public:
    outbuf() {
        // no buffering, overflow on every char
        setp(0, 0);
    }

    virtual int_type overflow(int_type c = traits_type::eof()) {
        // add the char to wherever you want it, for example:
        // DebugConsole.setText(DebugControl.text() + c);
        return c;
    }
};

int main() {
    // set std::cout to use my custom streambuf
    outbuf ob;
    std::streambuf *sb = std::cout.rdbuf(&ob);

    // do some work here

    // make sure to restore the original so we don't get a crash on close!
    std::cout.rdbuf(sb);
    return 0;

}

于 2009-02-10T16:42:29.617 回答
4

我需要从第三方库获取输出到 std::cout 和 std::cerr 并使用 log4cxx 记录它们,并且仍然保留原始输出。

这就是我想出的。这很简单:

  • 我用我自己的类替换了 ostream 的旧缓冲区(如 std::cout),这样我就可以访问写入它的内容。

  • 我还使用旧缓冲区创建了一个新的 std::ostream 对象,以便我可以继续将输出发送到我的控制台,除了将它发送到我的记录器。我觉得这很方便。

代码:

class intercept_stream : public std::streambuf{
public:
    intercept_stream(std::ostream& stream, char const* logger):
      _logger(log4cxx::Logger::getLogger(logger)),
      _orgstream(stream),
      _newstream(NULL)
    {
        //Swap the the old buffer in ostream with this buffer.
        _orgbuf=_orgstream.rdbuf(this);
        //Create a new ostream that we set the old buffer in
        boost::scoped_ptr<std::ostream> os(new std::ostream(_orgbuf));
        _newstream.swap(os);
    }
    ~intercept_stream(){
        _orgstream.rdbuf(_orgbuf);//Restore old buffer
    }
protected:
    virtual streamsize xsputn(const char *msg, streamsize count){
        //Output to new stream with old buffer (to e.g. screen [std::cout])
        _newstream->write(msg, count);
        //Output to log4cxx logger
        std::string s(msg,count);
        if (_logger->isInfoEnabled()) {
            _logger->forcedLog(::log4cxx::Level::getInfo(), s, LOG4CXX_LOCATION); 
        }
        return count;
    }
private:
    log4cxx::LoggerPtr _logger;
    std::streambuf*    _orgbuf;
    std::ostream&      _orgstream;
    boost::scoped_ptr<std::ostream>  _newstream;
};

然后使用它:

std::cout << "This will just go to my console"<<std::endl;
intercept_stream* intercepter = new intercept_stream(std::cout, "cout");
std::cout << "This will end up in both console and my log4cxx logfile, yay!" << std::endl;
于 2009-07-16T11:47:51.170 回答
1

对于 log4cxx 示例,您必须覆盖 overflow() 和 sync() 否则将始终在接收到第一个流后设置坏位。

请参阅: http ://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/fd9d973282e0a402/a872eaedb142debc

InterceptStream::int_type InterceptStream::overflow(int_type c)
{
    if(!traits_type::eq_int_type(c, traits_type::eof()))
    {
        char_type const t = traits_type::to_char_type(c);
        this->xsputn(&t, 1);
    }
    return !traits_type::eof();
}

int InterceptStream::sync()
{
    return 0;
}
于 2011-01-04T19:57:38.680 回答
0

如果您只想获取 ostringstream 的内容,请使用它的 str() 成员。例如:

string s = oss.str();    
于 2009-02-10T16:51:19.877 回答