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.