2010-03-11 72 views
9

不应该有一个简单的eol这样做吗?如何用boost :: spirit :: qi解析行尾?

#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

为什么后两个失败?


相关问题:

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

回答

13

您使用space作为队长为您来电phrase_parse。此解析器匹配std::isspace返回true的任何字符(假设您正在执行基于ascii的解析)。出于这个原因,输入中的\r\n被您的队长吃掉,然后您的eol解析器可以看到它们。

+1

使用'phrase_parse(it,end,p,space - eol)'允许'eol'成功。谢谢! – 2010-03-12 16:21:24

+1

@GregBacon当我输入'space-eol'时,我得到了非常奇怪而长的错误信息。 – Dilawar 2011-12-26 19:55:24

+1

@Dilawar看到这个答案http://stackoverflow.com/a/10469726/85371]的相关提示和技术来改变船长的行为 – sehe 2012-05-06 10:24:11

相关问题