1

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?

Christophe
  • 68,716
  • 7
  • 72
  • 138
mgr
  • 344
  • 4
  • 11
  • Why not simply use [`std::stod`](https://en.cppreference.com/w/cpp/string/basic_string/stof) or [`std::strtod`](https://en.cppreference.com/w/cpp/string/byte/strtof)? – Some programmer dude Feb 13 '19 at 07:25
  • @Someprogrammerdude certainly because these functions are not bothered with trailing non numeric chars after a valid numeric entry (e.g. if locale expects a dot and not a comma, the programme might understand 3 when user may type 3,1415 and nobody would notice the error since the data would be considered as correct. – Christophe Feb 13 '19 at 07:41
  • 1
    You can use the `pos` argument to detect trailing characters – Alan Birtles Feb 13 '19 at 07:43
  • 1
    @Christophe Those functions support checking for that too. `std::stod` with the `pos` argument and `std::strtod` with the `str_end` argument. – Some programmer dude Feb 13 '19 at 07:44
  • 1
    I tested performance of std::strtod against boost::spirit::x3::double_ (micro-benchmark with nonius) and it takes about 50% longer to test with this one. Also it uses errno... Will try std::from_chars next and post results here – mgr Feb 13 '19 at 13:35

1 Answers1

0

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.

mgr
  • 344
  • 4
  • 11