首页 > 解决方案 > 用逗号十进制字符为实数定义 strict_real_policies

问题描述

我想创建一个从 strict_real_policies 派生的自定义策略,它将解析实数,例如“3,14”,即在德国使用的逗号小数点。

这应该很容易,对吧?

标签: boost-spirit-x3

解决方案


#include <iostream>
#include <string>

#include <boost/spirit/home/x3.hpp>

template <typename T>
struct decimal_comma_strict_real_policies:boost::spirit::x3::strict_real_policies<T>
{
    template <typename Iterator>
        static bool
        parse_dot(Iterator& first, Iterator const& last)
        {
            if (first == last || *first != ',')
                return false;
            ++first;
            return true;
        }

};

void parse(const std::string& input)
{
    namespace x3=boost::spirit::x3;

    std::cout << "Parsing '" << input << "'" << std::endl;

    std::string::const_iterator iter=std::begin(input),end=std::end(input);
    const auto parser = x3::real_parser<double, decimal_comma_strict_real_policies<double>>{};
    double parsed_num;

    bool result=x3::parse(iter,end,parser,parsed_num);
    if(result && iter==end)
    {
        std::cout << "Parsed: " << parsed_num << std::endl;
    }
    else 
    {
        std::cout << "Something failed." << std::endl;
    }
}


int main() 
{
    parse("3,14");
    parse("3.14"); 
}

推荐阅读