Parse int or double using boost spirit (longest_d)(使用 boost 精神解析 int 或 double (longest_d))
问题描述
我正在寻找一种将字符串解析为 int 或 double 的方法,解析器应该尝试两种选择并选择匹配输入流最长部分的那个.
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.
有一个已弃用的指令 (longest_d) 完全符合我的要求:
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?
推荐答案
首先,切换到 Spirit V2 - 它已经取代了经典精神多年.
Firstly, do switch to Spirit V2 - which has superseded classical spirit for years now.
其次,您需要确保首选 int.默认情况下,double 可以同样好地解析任何整数,因此您需要使用 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 文档
查看测试程序在 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());
}
这篇关于使用 boost 精神解析 int 或 double (longest_d)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 boost 精神解析 int 或 double (longest_d)
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
