Hug*_*rrá 9 c++ boost boost-spirit boost-spirit-qi
我正在寻找一种方法来将字符串解析为int或double,解析器应该尝试两种方法并选择与输入流的最长部分匹配的方法.
有一个不推荐使用的指令(longest_d)正是我正在寻找的:
number = longest_d[ integer | real ];
Run Code Online (Sandbox Code Playgroud)
...因为它已被弃用,还有其他选择吗?如果有必要实现语义动作来实现所需的行为,有没有人有建议?
seh*_*ehe 15
首先,切换到精神V2 - 它已经取代古典精神多年了.
其次,您需要确保首选int.默认情况下,double可以同样好地解析任何整数,因此您需要使用strict_real_policies:
real_parser<double, strict_real_policies<double>> strict_double;
Run Code Online (Sandbox Code Playgroud)
现在你可以简单说明
number = strict_double | int_;
Run Code Online (Sandbox Code Playgroud)
看到
请参阅测试计划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());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1914 次 |
| 最近记录: |