> "ex" 不幸的是,这无法解析 1ex 完整示例代码: #include #include -6ren">
gpt4 book ai didi

c++ - 解析 float 后跟包含 "e"字符的字符串

转载 作者:搜寻专家 更新时间:2023-10-31 00:51:38 25 4
gpt4 key购买 nike

我正在尝试解析这种类型的字符串

1.2e3ex
1.2e3 ex

并已设置

x3::float_ >> "ex"

不幸的是,这无法解析

1ex

完整示例代码:

#include <iostream>
#include <boost/spirit/home/x3.hpp>
namespace x3 = boost::spirit::x3;

const auto parser = x3::float_ >> "em";

int main()
{
std::string input = "1em";
auto first = input.begin();
auto last = input.end();

float value{};
bool result = x3::phrase_parse(first, last, parser, x3::blank, value);

if(result)
{
if(first == last)
std::cout << "parse succesful: " << value << '\n';
else
std::cout << "incomplete parse: " << value << '\n';
}
else
std::cout << "parse unsuccesful\n";
}

可用live on Coliru

看来我需要跳过一些障碍,

struct non_scientific_float_policy : x3::real_policies<float>
{
template <typename Iterator>
static bool parse_exp(Iterator& first, Iterator const& last)
{
return false;
}
};

const auto non_scientific_float = x3::real_parser<float, non_scientific_float_policy>{};

provide an alternative :

const auto parser = non_scientific_float >> "em" | x3::float_ >> "em";

没有别的办法吗?

最佳答案

您可以通过调整真实策略 parse_exp 来解决此问题,指数检测不仅要期待 [eE] 字符,还要期待 [eE][ -+]?[0-9].

#include <iostream>
#include <boost/spirit/home/x3.hpp>
namespace x3 = boost::spirit::x3;

template <typename T>
struct alt_real_policies : x3::real_policies<T>
{
template <typename Iterator>
static bool parse_exp(Iterator& first, Iterator const& last)
{
Iterator save = first;
if (x3::real_policies<T>::parse_exp(first, last)) {
Iterator iter = first;
if (x3::extract_int<x3::unused_type, 10, 1, 1>::call(iter, last, x3::unused))
return true;
}
first = save;
return false;
}

};

const x3::real_parser<float, alt_real_policies<float>> altfloat;
const auto parser = altfloat >> "em";

int main()
{
std::string input = "1em";
auto first = input.begin();
auto last = input.end();

float value{};
bool result = x3::phrase_parse(first, last, parser, x3::blank, value);

if (result)
{
if (first == last)
std::cout << "parse succesful: " << value << '\n';
else
std::cout << "incomplete parse: " << value << '\n';
}
else
std::cout << "parse unsuccesful\n";
}

http://coliru.stacked-crooked.com/a/f60f334c960cb602

关于c++ - 解析 float 后跟包含 "e"字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54485356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com