【问题标题】:make std::ostream automatically ident when encountering special characters使 std::ostream 遇到特殊字符时自动识别
【发布时间】:2022-01-31 16:48:58
【问题描述】:

我希望有一些工具可以在遇到特殊字符(或特殊对象)时自动识别std::ostream(或派生的)。假设特殊字符是<>。在这种情况下,以下输入 test0<test1<test2, test3<test4> > > 应产生以下输出:

test0<
    test1<
        test2,
        test3<
            test4
        >
    >
>

如何实现这一点?

【问题讨论】:

  • 应该自己检测这些字符还是应该通过调用某些函数来强制缩进?在流中输出单个字符时改变行为是否足够?
  • @MarekR 唯一的限制是 std::ostream 的正常格式应该继续工作。
  • boost iostreams 可能会有所帮助

标签: c++ c++11 formatting ostream


【解决方案1】:

boost::iostreams 使这变得相当容易,您可以定义过滤器,然后将它们与输出流链接在一起,以将输入转换为所需的输出:

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

【讨论】:

  • 据我在 boost 源代码中看到的,newLine() 方法不是从外部调用的。它需要有一个布尔返回类型吗?
  • 需要通过put返回io::write的值
【解决方案2】:

std::ostream? IOStream 设计相当复杂(而且有点慢),所以我明白你为什么会这样想。 ostream 这个名字听起来像是一个很好的提示,但实际上并没有多大作用。通过将std::ostreambufoperator&lt;&lt; 重载绑定在一起,它确实有效。派生的ostream 类提供具体的流缓冲区。

您想要的可能是streambuf 过滤器。您获取底层流缓冲区,并将其用作输出,但是当您看到 &gt; 时插入一些额外的空格

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-25
    • 1970-01-01
    • 2020-12-18
    • 2018-02-10
    • 2018-09-25
    • 2013-11-07
    • 1970-01-01
    • 2011-06-12
    相关资源
    最近更新 更多