boost spirit qi numeric parsing of integer and floating points

后端 未结 2 1588
难免孤独
难免孤独 2020-12-17 03:09

i am trying to make sense of the following result. The test case code is

#include 
#include 

        
相关标签:
2条回答
  • 2020-12-17 03:35

    For your specific example, I think it's actually described in the Boost Spirit documentation under RealPolicies Specialization. To make things a bit easier for you, I whipped out a quick "real" parser, that only parses real numbers and not integers(or at least it worked with your simplified examples):

    template <typename T>
    struct strict_real_policies : qi::real_policies<T>
    {
        static bool const expect_dot = true;
    };
    
    qi::real_parser< double, strict_real_policies<double> > real;
    

    And you can use this just like any other parser(like int_ and double_). You might have to add:

    #include <boost/spirit/include/qi_numeric.hpp>
    

    To get it to compile.

    0 讨论(0)
  • 2020-12-17 03:41

    The problem with the double-not-int qi::double_ - qi::int_ is that an individual parser doesn't have to match the whole input to be a successful match. For "+12345.34", qi::double_ makes a successful match on the whole thing and qi::int makes a successful match on "+12345", so that qi::double_ - qi::int_ is a non-match. For difference operator, think about applying each parser separately and whether there is a valid match for each for even the first part of the input.

    You can get the behavior you want by requiring some kind of boundary after qi::int_. What follows when an qi::int_ matches the first part of a float is a valid float (e.g. qi::int_ on "+12345.34" matches "+12345", leaving ".34" next on the stream). Therefore, you can do a negative look ahead for a float:

    int_rule %= qi::int_ >> !qi::double_;
    
    double_rule %= qi::double_ - int_rule; 
    

    or

    double_rule %= qi::double_ - (qi::int_ >> !qi::double_); 
    

    !qi::double is also true for whitespace and eoi, so I think this should be pretty general for standard format. This won't work for scientific notation though.

    0 讨论(0)
提交回复
热议问题