rotis23>is isdigit part of standard c?
Yes.
rotis23>i think i might just check manually - using an ascii range
FWIW I have a few comments.
Checking the digits first may work fine. But consider that you will be doing the checking up front, and if the string contains only digits it sounds as if you will use atoi. It is quite possible that atoi itself calls strtol, which performs another check on the validity as it attempts to convert the data (but its error-checking results are thrown away). If performance is an issue, this double-checking may be a problem. My suggestion was that since you want error checking and strtol does this, maybe you could use it.
Code:
#include <stdlib.h>
#include <stdio.h>
int myatoi(const char *s, int *value)
{
if ( s != NULL && *s != '\0' && value != NULL )
{
char *endptr = s;
*value = (int)strtol(s, &endptr, 10);
if ( *endptr == '\0' )
{
return 1;
}
}
return 0; /* failed to convert string to integer */
}
int main(void)
{
int i, value = 2;
const char *text[] =
{
"0", "0x0", "0.0", "00", "15", "", NULL, "a", " 0", "-0", " +0",
};
for ( i = 0; i < sizeof(text)/sizeof(*text); ++i )
{
int result = myatoi(text[i], &value);
printf("text[%d] = \"%s\", value = %d (%s)\n", i,
text[i] ? text[i] : "<NULL>", value,
result ? "confirmed" : "error");
}
return 0;
}
/* my output
text[0] = "0", value = 0 (confirmed)
text[1] = "0x0", value = 0 (error)
text[2] = "0.0", value = 0 (error)
text[3] = "00", value = 0 (confirmed)
text[4] = "15", value = 15 (confirmed)
text[5] = "", value = 15 (error)
text[6] = "<NULL>", value = 15 (error)
text[7] = "a", value = 0 (error)
text[8] = " 0", value = 0 (confirmed)
text[9] = "-0", value = 0 (confirmed)
text[10] = " +0", value = 0 (confirmed)
*/
Some of these results may not be what you want, so first checking for all digits may be necessary. But if the behavior of strtol is what you need, then you could skip the double-checking.
<nitpicks>
Magos>#define FirstDigit 48
This is less portable than #define FirstDigit '0'.
Monster,Magos>bool, true, false
C++, not C.
</nitpicks>