2

How to parse a string which may contain either double or int depending on whether the dot is set. E.g. 6.0 is of double type and 6 is of int type. The rule would be

rule<it,boost::variant<int,double>,skipper> r = qi::double_|qi::int_;

However, a stream will be fed by double as for all numbers in this case.

alexander.sivak
  • 4,352
  • 3
  • 18
  • 27
  • related: ["Parse int or double using boost spirit"](http://stackoverflow.com/q/13261502/2378523) – sehe Jul 01 '13 at 07:05

2 Answers2

4

In addition to the pragmatic approach1 given by interjay, have a look at real_parser_policies:

real_parser<double,strict_real_policies<double>>() | int_

would be equally good.


1 which I sometimes use myself (you should be able to find an answer doing this on SO). Note, however that there are problems when the input is e.g. 123e-5 (which would parse an int, leaving e-5 unparsed).

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
  • 123e-5 should be parsed: floating_literal = -sign >> ( nan | inf | fractional_constant >> !exponent_part | +digit >> exponent_part ) ;exponent_part = (lit('e') | 'E') >> -sign >> +digit ; – alexander.sivak Jul 10 '13 at 16:09
0

I think this should work:

(int_ >> !lit('.')) | double_

It will match an integer only if it isn't followed by a dot. Otherwise, it will match a double.

interjay
  • 107,303
  • 21
  • 270
  • 254
  • If you want less heavy backtracking, use the strict real policy – sehe Jul 01 '13 at 07:04
  • Also, -1 as this answer does not work correctly for Inf/NaN/exponential notation (think about `1e10`, e.g.) – sehe Jul 01 '13 at 07:06