I'm dealing with an char[] containing text which should represent a double number value OR a long number.
I'm in a need to write a function that detects which of the above data-types is represented (if any).
I thought about using strtol() and check if it fails to parse the entire string, and if it fails, using strtod().
I would be happy to see whether there is a better option to do so.
Thanks.
I thought about using strtol() and check if it fails to parse the entire string, and if it fails, using strtod().
I think that's a good idea and I don't think there is a better one. Implementing your own parsing routine is generally a bad idea.
I would trim the string from trailing whitespace before calling strtol
to avoid false negatives.
strtol()
and strtod()
is the right approach. Be sure to use errno
to detect integer overflow. 2 stand-alone functions follow:
int Is_long(const char *src, long *dest) {
char *endptr;
// Clear, so it may be tested after strtol().
errno = 0;
// Using 0 here allows 0x1234, octal 0123 and decimal 1234.
long num = strtol(src, &endptr, 0);
// If +/- overflow, "" or has trailing text ...
if (errno || endptr == src || *endptr != '\0') {
return 0;
}
if (dest) *dest = num;
return 1;
}
int Is_double(const char *src, double *dest) {
char *endptr;
// In this case, detecting over/undeflow IMO is not a concern, so ignore it.
double num = strtod(src, &endptr);
// If "" or has trailing text ...
if (endptr == src || *endptr != '\0') {
return 0;
}
if (dest) *dest = num;
return 1;
}
@Klas Lindbäck does bring up the good point of what to do about trailing white-space. This answer assumes it is not valid.
You can use the following code to detect that.
char* isDouble = strchr(string, '.');
if (isDouble) {
// is Double here
}else {
// is long here
}