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

Parse int or double using boost spirit (longest_d)


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?


Solution

  • 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());
    }