Do not use atof . Instead, use strtod , from <cstdlib> , and also note errno from <cerrno> :
// assume: "char * mystr" is a null-terminated string char * e; errno = 0; double x = std::strtod(mystring, &e); if (*e != '\0' || // error, we didn't consume the entire string errno != 0 ) // error, overflow or underflow { // fail }
Pointer e indicates one after the last character consumed. You can also check e == mystr to see if any characters were used.
There is also std::wcstod for working with wchar_t strings, from <cwstring> .
In C ++ 11, you also have std::to_string / std::to_wstring , from <string> , but I believe that this throws an exception if the conversion fails, which may not be the desired failure mode when working with external data .
Kerrek SB
source share