Search code examples
c++boostboost-spiritboost-spirit-x3

How to do "stream" parsing in Boost Spirit X3?


I am trying to find out the correct way to parse from an istream using x3. Older docs refer to multi_pass stuff, can I still use this? Or is there some other way to buffer streams for X3 so that it can backtrack ?


Solution

  • You can still use this. Just include

    #include <boost/spirit/include/support_istream_iterator.hpp>
    

    Example Live On Coliru

    #include <boost/spirit/home/x3.hpp>
    #include <boost/spirit/include/support_istream_iterator.hpp>
    #include <iostream>
    #include <sstream>
    
    int main() {
        std::istringstream iss("{ 123, 234, 345, 456, 567, 678, 789, 900, 1011 }");
        boost::spirit::istream_iterator f(iss), l;
    
        std::vector<int> values;
    
        namespace x3 = boost::spirit::x3;
    
        if (x3::phrase_parse(f, l, '{' >> (x3::int_ % ',') >> '}', x3::space, values)) {
            std::cout << "Parse results:\n";
            for (auto v : values) std::cout << v << " ";
        } else
            std::cout << "Parse failed\n";
    }
    

    Prints

    Parse results:
    123 234 345 456 567 678 789 900 1011