Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if atof or _wtof failes?

Tags:

c++

How to detect if atof or _wtof failes to convert the string to double? But not by trying to check if the result is different form 0.0 because my input can be 0.0. Thanks!

like image 581
jondoe Avatar asked Sep 11 '12 11:09

jondoe


1 Answers

Don't use atof. Instead, use strtod, from <cstdlib>, and also check 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
}

The pointer e points one past the last consumed character. You can also check e == mystr to see if any characters got consumed.

There's 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 throws an exception if the conversion fails, which may not be a desirable failure mode when dealing with external data.

like image 76
Kerrek SB Avatar answered Sep 21 '22 23:09

Kerrek SB