Search code examples
c++boost-spirit

Boost spirit parser of Fortran printed doubles


I am using num_list3.cpp from Boost Spirit examples. I am testing the variety of the double types it can parse. I used the following list:

1.2,0.2
.2,5.
1.e+23,.23E4
0e+10
1.3D+3

I noticed that it fails on parsing the last number 1.3D+3.

How could I set D as an exponent prefix of a double?


Solution

  • You can easily do that with Boost.Spirit. You just need to instantiate a real_parser with a custom policy that takes care of the "d|D" prefix. It could be as simple as:

    template <typename Type>
    struct fortran_policy : qi::real_policies<Type>
    {
        template <typename Iterator>
        static bool parse_exp(Iterator& first, const Iterator& last)
        {
            if (first == last || (*first != 'e' && *first != 'E' && *first != 'd' && *first != 'D'))
                return false;
            ++first;
            return true;
        }
    };
    

    Then you would simply need to use:

    qi::real_parser<double,fortran_policy<double>> double_;
    

    without needing to change anything else(although that semantic action seems rather unnecessary).

    Live on ideone