1

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?

Exagon
  • 4,798
  • 6
  • 25
  • 53
  • 2
    Saying just "it doesn't work" is not telling us anything that can help you. Please describe ***how*** "it doesn't work". Do you get build errors? Crashes at runtime? Wrong results? The more details the better. If you get build errors you should copy-paste the errors (in full and complete) *as text* unedited into the body of the question. If you get unexpected results then tell us your input and the actual *and expected* output. If you get crashes then run in a debugger to locate the crash. Also please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). – Some programmer dude Jul 24 '16 at 12:54
  • @JoachimPileborg : In this case, it doesn't work in the same way my car doesn't swim – the library just isn't _for_ that. But if the OP knew that, they wouldn't be asking this quesiton in the first place... ;-] – ildjarn Jul 24 '16 at 12:57
  • 2
    This parser should parse a series of numbers into a string: std::string input = "1234"; std::string out; x3::phrase_parse(input.begin(), input.end(), +x3::digit, x3::space, out); assert(out == input); (meaning 1 or more digits. The 'digit' parser's attribute is 'char' so when you put a plus in front, you get a vector of char or string). – matiu Jul 25 '16 at 06:04

1 Answers1

1

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!

ildjarn
  • 62,044
  • 9
  • 127
  • 211