查询std::ostringstream内容

4

不使用std::ostringstream::str()成员函数创建std::string进行搜索,是否有可能搜索std::ostringstream的内容?

我有以下代码,并希望避免在每次调用flush_()时构造std::string实例:

#include <iostream>
using std::cout;

#include <ios>
using std::boolalpha;

#include <sstream>
using std::ostringstream;

#include <string>
using std::string;

class line_decorating_ostream
{
public:
    line_decorating_ostream()  { out_ << boolalpha;  }
    ~line_decorating_ostream() { cout << out_.str(); }

    template <typename T>
    line_decorating_ostream& operator<<(const T& a_t)
    {
        out_ << a_t;
        flush_();
        return *this;
    }

private:
    ostringstream out_;
    line_decorating_ostream(const line_decorating_ostream&);
    line_decorating_ostream& operator=(const line_decorating_ostream&);

    // Write any full lines.
    void flush_()
    {
        string s(out_.str());
        size_t pos = s.find('\n');
        if (string::npos != pos)
        {
            do
            {
                cout << "line: [" << s.substr(0, pos) << "]\n";
                s = s.substr(pos + 1);

            } while (string::npos != (pos = s.find('\n')));

            out_.clear();
            out_.str("");
            out_ << boolalpha << s;
        }
    }
};

int main()
{
    line_decorating_ostream logger;

    logger << "1 " << "2 " << 3 << " 4 " << 5 << "\n"
           << "6 7 8 9 10\n...\n" << true << "\n";

    return 0;
}

[我不担心它会导致任何性能问题,只是好奇是否可能。]

1个回答

4
使用其streambuf类?还是编写自己的类?(好吧:你应该编写自己的类:pbasepptr是受保护的。)
class my_str_buffer : public basic_stringbuf<char>
{
  public:
    using basic_stringbuf<char>::pbase;
    using basic_stringbuf<char>::pptr;
};

my_str_buffer my_buf;
ostream str( &my_buf );
// do anything
string foo( str.rdbuf()->pbase(), str.rdbuf()->pptr() );

ostream constructor and stringbuf


+1 谢谢。只是需要注意,我必须使用 dynamic_cast<my_str_buffer*>(str.rdbuf()) 来访问 pbasepptr - hmjd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接