Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a string is an integer or a float in ANSI C

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)?

like image 953
Christopher Dolan Avatar asked Sep 16 '08 23:09

Christopher Dolan


1 Answers

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.

like image 197
Patrick_O Avatar answered Sep 23 '22 06:09

Patrick_O