Reputation: 12294
I'm considering to use the strtod() function to convert a string to a double in C, which siganture is:
double strtod (const char* str, char** endptr);
being str
the string to be converted and endptr
a pointer to be set to to the first character after the number.
Documentation says:
On success, the function returns the converted floating point number as a value of type double. If no valid conversion could be performed, the function returns zero (0.0).
Thus, as far as I understand, it is not possible to detect situations in which str
has a format error (e.g. "foo", "-3ab" or "3o3") from situations in which the str
represents 0 (e.g. "0", "0.000", "-0.0", "0e10").
How strtod() function could be used avoiding that problem in zero conversion?
EDIT: I have seen a similar question here. However, I think I'm not asking the same, as my question is about the ambiguity problem between 0 and wrongly formated string, while that other post is about detecting formating errors in general.
Upvotes: 1
Views: 608
Reputation: 448
Also, if you want to detect other errors, like "3.14xyz", strtod will return 3.14, but endptr will point to the 'x', so, if after strtod, 'endptr' is not pointing to 'str' AND 'endptr' points to only whitespace (or EXACTLY 0 if you want to be strict), then 'str' is indeed a valid float. Also errno is set to ERANGE if the string 'str' would provoke an overflow.
Here is an implementation of it:
bool isDouble(const char* s)
{
char* rest = (char*) s;
strtod(s, &rest);
if ((rest == s) || (errno == ERANGE))
return false;
// If all WS after the last char used in the conversion, then the string is considered a 'clean float'
while ((*rest == ' ') || (*rest == '\t') || (*rest == '\n'))
++rest;
return (*rest == 0);
}
Upvotes: 2
Reputation: 46331
That's precisely why you have endptr
. If after the call endptr == str
, then no number was parsed.
Upvotes: 2