2010-03-11 10 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

आप कप्तान अपने कॉल phrase_parse करने के लिए के रूप में space उपयोग कर रहे हैं। यह पार्सर किसी भी चरित्र से मेल खाता है जिसके लिए std::isspace सत्य लौटाता है (मान लीजिए कि आप एसीआई आधारित पार्सिंग कर रहे हैं)। इस कारण से आपके eol पार्सर द्वारा देखा जा सकता है इससे पहले इनपुट में \r\n आपके कप्तान द्वारा खाया जाता है।

+1

'phrase_parse (it, end, p, space-eol)' का उपयोग करके 'eol' को सफल होने की अनुमति दी गई। धन्यवाद! –

+1

@GregBacon जब मैं 'space - eol' टाइप करता हूं, तो मुझे बहुत अजीब और लंबा त्रुटि संदेश मिलता है। – Dilawar

+1

@ डिलावर इस जवाब को देखें http://stackoverflow.com/a/10469726/85371] कप्तान व्यवहार को बदलने के लिए संबंधित संकेतों और तकनीकों के लिए – sehe

संबंधित मुद्दे