Thursday, February 5, 2009

C - isNumeric (A Simple Function to test given string is Numeric)

This a boolean function which takes a string and tells whether it is a numeric string (floating point and negative numbers included).

Function returns true (non-zero) if character-string parameter represents a signed or unsigned integer. Otherwise returns false (zero).


int isNumeric (const char * s)
{
if (!s || !*s)
return 0;
char * p;
strtol (s, &p, 10); // For testing Integer
return !*p;
}


The above Code is for testing integer only.
Replace strtol (s, &p, 10); with
strtod(s, &p); // For testing double.


For Unicode you can use
int isDouble (const TCHAR * s)
{
if (!s || !*s)
return 0;
TCHAR * p;
wcstod(s, &p);
return !*p;
}

No comments: