LogicalKip
LogicalKip

Reputation: 522

How to use the parse/phrase_parse function

Concretely, using the grammar g, how do I parse the string s ? What arguments should I give ? I've tried many calls and always got errors.

Also, since I'm not sure yet which one I will use later, would there be any difference using phrase_parse instead ?

namespace qi = boost::spirit::qi;
int main() {
    My_grammar<std::string::const_iterator> g;
    std::string s = "a"; // string to parse
    if (qi::parse( /*...*/ )) {
        std::cout << "String parsed !";
    } else {
        std::cout << "String doesn't parse !";
    }
    return EXIT_SUCCESS;
}

Upvotes: 2

Views: 785

Answers (2)

Chris Beck
Chris Beck

Reputation: 16224

Basically, you should look in the tutorial, but part of the issue is, you more or less need to create a variable to hold the start iterator. Because, it is passed by reference to qi::parse, and where exactly it stops can be considered an output of the qi::parse function. If you try to pass it by s.begin() it won't work because then you are trying to bind a reference to a temporary.

namespace qi = boost::spirit::qi;
int main() {
    My_grammar<std::string::const_iterator> g;
    std::string s = "a"; // string to parse
    std::string::const_iterator it = s.begin(); // The type declaration here
    std::string::const_iterator end = s.end(); // and here needs to match template parameter
                                               // which you used to instantiate g

    if (qi::parse( it, end, g )) {
        std::cout << "String parsed !";
    } else {
        std::cout << "String doesn't parse !";
    }
    return EXIT_SUCCESS;
}

You use phrase_parse only when you want to explicitly specify a skip grammar.

Upvotes: 3

sehe
sehe

Reputation: 393829

Yes there will be a difference.

phrase_parse uses a skipper and might not consume all input and still return true.

In all other respects, the two are identical. You should really just hit the documentation:

 std::string::const_iterator f(s.begin(), l(s.end());

 if (qi::parse(f, l, g/*, optional, bound, attribute, references*/))

Upvotes: 3

Related Questions