我希望有一些工具,使std::ostream (或派生)在遇到特殊字符(或特殊对象)时自动识别。让我们假设特殊字符是<和>。在这种情况下,以下输入test0<test1<test2, test3<test4> > >应该产生以下输出:
test0<
test1<
test2,
test3<
test4
>
>
>我们将如何实现这一目标?
发布于 2022-01-31 18:03:44
助推::碘流使这相当容易,您可以定义过滤器,然后将它们与输出流链接在一起,以将输入转换为所需的输出:
#include <iostream>
#include <boost/iostreams/filtering_stream.hpp>
namespace io = boost::iostreams;
struct QuoteOutputFilter {
typedef char char_type;
typedef io::output_filter_tag category;
int indent = 0;
template<typename Sink>
bool newLine(Sink& snk)
{
std::string str = "\n" + std::string(indent * 4, ' ');
return io::write(snk, str.c_str(), str.size());
}
template<typename Sink>
bool put(Sink& snk, char c)
{
switch (c)
{
case '<':
io::put(snk, c);
indent += 1;
return newLine(snk);
case ',':
io::put(snk, c);
return newLine(snk);
case '>':
indent -= 1;
newLine(snk);
return io::put(snk, c);
default:
return io::put(snk, c);
}
}
};
int main()
{
io::filtering_ostream out;
out.push(QuoteOutputFilter());
out.push(std::cout);
out << "test0<test1<test2, test3<test4> > >";
}发布于 2022-01-31 17:08:20
std::ostream?IOStream的设计相当复杂(而且有点慢),所以我可以理解为什么您会这样认为。ostream这个名字听起来像是一个很好的提示,但它实际上并没有多大作用。它实际上是通过将std::ostreambuf和operator<<重载绑定在一起工作的。派生的ostream类提供了具体的流。
您想要的可能是一个streambuf过滤器。获取底层的streambuf,并将其用作输出,但在看到>时插入一些额外的空格。
https://stackoverflow.com/questions/70929696
复制相似问题