Using only ANSI C, what is the best way to, with fair certainty, determine if a C style string is either a integer or a real number (i.e float/double)?
Don't use atoi and atof as these functions return 0 on failure. Last time I checked 0 is a valid integer and float, therefore no use for determining type.
use the strto{l,ul,ull,ll,d} functions, as these set errno on failure, and also report where the converted data ended.
strtoul: http://www.opengroup.org/onlinepubs/007908799/xsh/strtoul.html
this example assumes that the string contains a single value to be converted.
#include <errno.h>
char* to_convert = "some string";
char* p = to_convert;
errno = 0;
unsigned long val = strtoul(to_convert, &p, 10);
if (errno != 0)
// conversion failed (EINVAL, ERANGE)
if (to_convert == p)
// conversion failed (no characters consumed)
if (*p != 0)
// conversion failed (trailing data)
Thanks to Jonathan Leffler for pointing out that I forgot to set errno to 0 first.
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