-1

I want to convert a char * to a double in c++. But before do that, I want to check that the char * is a right double number. So I have made this code :

bool                    Tools::m_CheckIfDouble(char *p_nb)
{
    if (p_nb == NULL)
        return (false);
    for (unsigned int v_i = 0; p_nb[v_i]; v_i++)
        if ((p_nb[v_i] < '0' || p_nb[v_i] > '9') && (p_nb[v_i] != '.' && p_nb[v_i] != '-'))
            return (false);
    return (true);
}

but I don't know how to check the char * for a double overflow (if the value of the char * is greater than the value of DBL_MAX or lesser than DBL_MIX).

Adrien A.
  • 441
  • 2
  • 12
  • 31

1 Answers1

2

The standard library function strtod should do the trick:

#include <cstdlib>
#include <cerrno>

double convert(char const * str)
{
    char * e;
    double res = std::strtod(str, &e);

    if (e == str || *e != 0) { /* error (invalid string) */ }

    if ((res == HUGE_VAL || -res == HUGE_VAL) && errno == ERANGE) { /* overflow */ }

    if (res == 0 && errno == ERANGE) { /* underflow */ }

    return res;
}

You get the idea; you can customize the error handling to your own requirements.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • @AJG85: That would not only defeat the purpose of having sensible error checking, but `strtod` is part of C89 and C++98, so it's always been in both standards. – Kerrek SB Nov 06 '12 at 04:14
  • Ah yes so it is. It just looks like one of the new C++11 functions as @aelnajjar pointed out. – AJG85 Nov 06 '12 at 04:30