c++ - 使用 boost spirit (longest_d) 解析 int 或 double

标签 c++ boost boost-spirit boost-spirit-qi

我正在寻找一种将字符串解析为 int 或 double 的方法,解析器应该尝试这两种选择并选择与输入流的最长部分匹配的那个。

有一个已弃用的指令 (longest_d) 完全符合我的要求:

number = longest_d[ integer | real ];

...既然它已被弃用,还有其他选择吗?如果有必要实现语义操作来实现所需的行为,有人有什么建议吗?

最佳答案

首先,请切换到 Spirit V2 - 多年来它已经取代了经典 spirit 。

其次,您需要确保首选 int。默认情况下,double 可以很好地解析任何整数,因此您需要改用 strict_real_policies:

real_parser<double, strict_real_policies<double>> strict_double;

现在你可以简单的声明

number = strict_double | int_;

查看测试程序 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());
}

关于c++ - 使用 boost spirit (longest_d) 解析 int 或 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13261502/

相关文章:

c++ - CMake 在 Debian 上找不到 boost_program_options

c++ - 是否有任何编译器忽略有关默认内联函数的 C++ 标准?

c++ - QGraphicsScene 中没有显示任何内容

c++ - 带有插槽语义的超薄C++信号/事件机制

c++ - 顺序序列容器或如何打包 vector

c++ - 帮助提升精神 AST

c++ - 为什么这段代码总是返回零文件大小?

c++ - OpenCV cpp 运动检测

c++ - 如何在找到某个单词后解析数字

C++ spirit boost : Making a input iterator into a forward iterator