Search code examples
c++parsingc++14boost-spiritboost-spirit-x3

Parsing a number into a string with boost spirit x3


I would like to parse various numbers with spirit x3 into a string. I tried to do it like this, but it doesnt work.

typedef x3::rule<class int_parser_id, std::string> int_parser_type;
const int_parser_type int_parser = "int_parser";
auto const int_parser_def = x3::int32;

what can I do to parse a Int with the x3::int32 parser into a string?


Solution

  • Parsing is scanning a string in order to produce objects of a concrete type or set of types; what you're asking for is the opposite of that, which Spirit calls 'generation'. Spirit.X3 performs parsing only, so the answer to your direct question is: You can't.

    However, Spirit does come with a separate component for generation: Spirit.Karma.

    namespace karma = boost::spirit::karma;
    
    int const i = /*...*/;
    std::string str;
    karma::generate(std::back_inserter(str), karma::int_, i);
    

    Online Demo

    It must be noted that Karma is a C++03 codebase, and consequently has much longer compilation times than X3 – use of precompiled headers is highly recommended!