【问题标题】:How do I parse end-of-line with boost::spirit::qi?如何使用 boost::spirit::qi 解析行尾?
【发布时间】:2011-01-26 15:13:01
【问题描述】:

不应该一个简单的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);
}

输出:

“富”:
  - 成功!
“富\n”:
  - 解析失败; r=0
“富\r\n”:
  - 解析失败; r=0

为什么后两者都失败了?


相关问题:

Using boost::spirit, how do I require part of a record to be on its own line?

【问题讨论】:

    标签: c++ boost-spirit eol boost-spirit-qi


    【解决方案1】:

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

    【讨论】:

    • 使用phrase_parse(it, end, p, space - eol) 允许eol 成功。谢谢!
    • @GregBacon 当我输入 space - eol 时,我会收到非常奇怪且很长的错误消息。
    • @Dilawar 请参阅此答案stackoverflow.com/a/10469726/85371] 了解改变船长行为的相关提示和技术
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多