Monday, January 04, 2010

detecting a floating point number on input in C

This could be useful code in the future. Found in comments on stackoverflow:
// convert input string to double int isfloat (const char *s) { char *ep = NULL; double f = strtod (s, &ep); if (!ep || *ep) return false; // has non-floating digits after number, if any return true; }
and
// distinguish between floats and ints int isfloat (const char *s) { char *ep = NULL; long i = strtol (s, &ep); if (!*ep) return false; // it's an int if (*ep == 'e' || *ep == 'E' || *ep == '.') return true; return false; // it not a float, but there's more stuff after it }