As per MSDN:
strtod
returns 0 if no conversion can be performed or an underflow occurs.
What if my string equals to zero (i.e., 0.0000)? How can I know if there is no error from the conversion?
OK, I use the following code to verify the idea:
char *Y = "XYZ";
double MyNum;
char *MyEndPtr;
int Err_Conversion = 0;
errno = 0; //reset
MyNum = strtod (Y, &MyEndPtr);
if ( (MyNum == 0) && (errno != 0) && (strcmp(Y, MyEndPtr) == 0) )
{ Err_Conversion = 1; }
I see that MyNum = 0, but never see the content of Y copied into MyEnPtr, or errno = 0 in this forced error. Any idea?
Use the
str_end
parameter of the function. For example:If conversion totally fails,
str
will equalstr_end
:You can combine these two methods to make sure the string was (completely) successfully converted (that is, by checking
str != str_end && *str_end == '\0'
)The signature is (give or take
restrict
keywords):If you pass a non-null pointer as the second argument, it will be returned with the value of
nptr
if it could perform no conversion. If it found a genuine zero in the input string, then the value stored in*endptr
won't benptr
.You can also look at
errno
, but you need to zero it before the call because no function in the standard C library or the POSIX library setserrno
to zero.The standard says: