Search code examples
boost-spirit-x3

Defining strict_real_policies for reals with a comma decimal character


I would like to create a custom policy derived from strict_real_policies that will parse reals, such as "3,14", i.e. with a comma decimal point as used e.g. in Germany.

That should be easy, right?


Solution

  • #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"); 
    }