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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With