使用Boost Spirit(longest_d)解析int或double

9

我正在寻找一种将字符串解析为整数或双精度浮点数的方法,解析器应该尝试两个方案,并选择匹配输入流最长部分的方案。

有一个已弃用的指令(longest_d)正是我需要的:

number = longest_d[ integer | real ];

由于它已被弃用,是否有其他替代方案?如果需要实现语义动作以实现所需的行为,是否有建议?

1个回答

15

首先,确保切换到 Spirit V2 - 这已经替代了经典的 Spirit 很多年了。

其次,您需要确保 int 得到优先。默认情况下,double 可以同样良好地解析任何整数,因此您需要改用 strict_real_policies

real_parser<double, strict_real_policies<double>> strict_double;

现在你可以简单地陈述

number = strict_double | int_;

请参阅

请参阅测试程序 在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());
}

我可能不理解问题的情境,但是 number=double_|int_ 不就可以工作吗? - user1252091
1
@llonesmiz 是的,real_parser<double,strict_real_policies<double>>()|int_ 也可以正常工作。 - Hugo Corrá
(int_ - double_) 总是无法解析吗?因为每个 int 都可以被解析为 double? - interjay
1
顺序不应该反过来为 number = strict_double | int_ 吗?假设它是从左到右解析的。 - Algebraic Pavel
@UndefinedPavel 当然,你是完全正确的。现在已经添加了一个测试程序,使用修复后的版本 :) (排序是旧版答案的遗留问题。显然,我成功地搞砸了两次...) - sehe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接