解析int或double使用boost精神(longest_d) [英] Parse int or double using boost spirit (longest_d)

查看:201
本文介绍了解析int或double使用boost精神(longest_d)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来解析字符串为int或双,分析器应该尝试两种选择,选择一个相匹配的输入流中最长的部分。

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.

有一个去precated指令(longest_d)这不正是我要找的:

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

number = longest_d[ integer | real ];

...因为它是德precated,还有​​其他的选择吗?如果有必要实现语义动作来实现所期望的行为,没有任何人有一个建议?

...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?

推荐答案

首先,请切换到精神V2 - 这已经取代了的经典的精神,多年来

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

其次,你需要确保一个int获取preferred。默认情况下,双可以解析任意整数同样出色,所以你需要使用 strict_real_policies 而不是:

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;

现在你可以简单地说明

number = strict_double | int_;

请参阅

  • realpolicies documentation

请参阅测试程序的 住在Coliru

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

这篇关于解析int或double使用boost精神(longest_d)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆