9

I'm looking for a way to parse a string as an int or a double, the parser should try both alternatives and choose the one matching the longest portion of the input stream.

There is a deprecated directive (longest_d) that does exactly what I'm looking for:

number = longest_d[ integer | real ];

...since it's deprecated, there are any other alternatives? In case it's necessary to implement a semantic action to achieve the desired behavior, does anyone have a suggestion?

Hugo Corrá
  • 14,546
  • 3
  • 27
  • 39

1 Answers1

15

Firstly, do switch to Spirit V2 - which has superseded classical spirit for years now.

Second, you need to make sure an int gets preferred. By default, a double can parse any integer equally well, so you need to use strict_real_policies instead:

real_parser<double, strict_real_policies<double>> strict_double;

Now you can simply state

number = strict_double | int_;

See

See test program Live on Coliru

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

using namespace boost::spirit::qi;

using A  = boost::variant<int, double>;
static real_parser<double, strict_real_policies<double>> const strict_double;

A parse(std::string const& s)
{
    typedef std::string::const_iterator It;
    It f(begin(s)), l(end(s));
    static rule<It, A()> const p = strict_double | int_;

    A a;
    assert(parse(f,l,p,a));

    return a;
}

int main()
{
    assert(0 == parse("42").which());
    assert(0 == parse("-42").which());
    assert(0 == parse("+42").which());

    assert(1 == parse("42.").which());
    assert(1 == parse("0.").which());
    assert(1 == parse(".0").which());
    assert(1 == parse("0.0").which());
    assert(1 == parse("1e1").which());
    assert(1 == parse("1e+1").which());
    assert(1 == parse("1e-1").which());
    assert(1 == parse("-1e1").which());
    assert(1 == parse("-1e+1").which());
    assert(1 == parse("-1e-1").which());
}
sehe
  • 374,641
  • 47
  • 450
  • 633
  • It's possible that I don't understand the scenario of the question but wouldn't `number=double_|int_` just work? –  Nov 07 '12 at 11:59
  • 1
    @llonesmiz Yes, real_parser>()|int_ works fine too. – Hugo Corrá Nov 07 '12 at 15:56
  • Doesn't `(int_ - double_)` always fail to parse, because every int can be parsed as a double? – interjay Jul 01 '13 at 10:38
  • 1
    Shouldn't the order be reversed to `number = strict_double | int_`? Assuming it tries to parse from left to right. – Algebraic Pavel Nov 21 '13 at 21:15
  • @UndefinedPavel You're absolutely right, of course. Added a test program now with the fixed version :) (_The ordering was a relict from an older version of this answer. Apparently, I managed to fudge it twice..._) – sehe Nov 21 '13 at 21:52