不应该是一个简单的 eol 做这件事吗?

#include <algorithm>
#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <string>
using boost::spirit::ascii::space;
using boost::spirit::lit;
using boost::spirit::qi::eol;
using boost::spirit::qi::phrase_parse;

struct fix : std::unary_function<char, void> {
  fix(std::string &result) : result(result) {}
  void operator() (char c) {
    if      (c == '\n') result += "\\n";
    else if (c == '\r') result += "\\r";
    else                result += c;
  }
  std::string &result;
};

template <typename Parser>
void parse(const std::string &s, const Parser &p) {
  std::string::const_iterator it = s.begin(), end = s.end();
  bool r = phrase_parse(it, end, p, space);
  std::string label;
  fix f(label);
  std::for_each(s.begin(), s.end(), f);
  std::cout << '"' << label << "\":\n" << "  - ";
  if (r && it == end) std::cout << "success!\n";
  else std::cout << "parse failed; r=" << r << '\n';
}

int main() {
  parse("foo",     lit("foo"));
  parse("foo\n",   lit("foo") >> eol);
  parse("foo\r\n", lit("foo") >> eol);
}

输出:

"foo":
  - success!
"foo\n":
  - parse failed; r=0
"foo\r\n":
  - parse failed; r=0

为什么后两者会失败呢?


相关问题:

使用 boost::spirit,如何要求记录的一部分独占一行?

有帮助吗?

解决方案

您正在使用 space 作为调用phrase_parse 的船长。该解析器匹配任何字符 std::isspace 返回 true(假设您正在进行基于 ASCII 的解析)。为此 \r\n 输入中的内容在你的船长看到之前就被你的船长吃掉了 eol 解析器。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top