Search code examples
c++validationparsingboost-spirit-x3

How to test string for valid double content with boost::spirit::x3?


I am trying to determine if a given string is a valid double representation. The code I am using looks like this:

bool testNumeric(const std::string& s)
{
    try
    {
        const auto doubleParser = boost::spirit::x3::double_;
        auto iter = s.begin();
        auto end_iter = s.end();
        double result = 0.;
        boost::spirit::x3::parse(iter, end_iter, doubleParser, result);
        return iter == end_iter;
    }
    catch (...)
    {
        return false;
    }
}

I am not interested in the resulting double (for now). If I give this function an input of "1e10000000", which is obviously too large for double, the program fails with an assertion (BOOST_ASSERT). Can this somehow be changed to either fail by return code or throw an exception, which I can catch? Or do I have to write my own double parser with spirit::x3?


Solution

  • In the end, I created a custom parsing method which first uses boost::spirit::x3::int_ on the exponent part of the double's string representation (if it exists) and returns if the exponent does not satisfy the bounds of the double type. Afterwards I call the boost::spirit::x3::double_ parser on valid strings.