本文介绍了查询std :: ostringstream内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以搜索 std :: ostringstream
的内容,而不使用 std :: ostringstream :: str()
成员函数创建一个 std :: string
来搜索?
Is it possible to search the content of a std::ostringstream
without using the std::ostringstream::str()
member function to create a std::string
to search?
避免在每次调用 flush _()
时构造 std :: string
实例:
I have the following and want to avoid constructing a std::string
instance on every invocation of flush_()
:
#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;
}
[它不会引起我担心的任何性能问题]
推荐答案
使用类?还是自己写一个? (Ok:你应该自己写一个: pbase
和 pptr
都受到保护。)
Use its streambuf
class? Or write an own one? (Ok: you should write an own one: pbase
and pptr
are protected.)
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
这篇关于查询std :: ostringstream内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!