strtoul
will set endptr
to point to the first non-digit character in the input string; however, it doesn't catch the sign (because, after all, you are allowed to write unsigned int x = -1;
).
So you'll have to do this in two stages; first, you'll have to look for the leading -
; if you don't find it, use strtoul
to do the conversion and check endptr
:
char input[N];
char *p;
while ( fgets( input, sizeof input, input_stream ) )
{
p = input;
while ( isspace( *p ) ) // skip over any leading whitespace
p++;
if ( !isdigit( *p ) )
{
printf( "\"%s\" is not a valid unsigned integer string\n" );
}
else
{
char *endptr;
unsigned int val = (unsigned int ) strtoul( p, &endptr, 0 );
if ( isspace( *endptr) || *endptr == 0 )
printf( "\"%s\" is a valid unsigned integer string: %u\n", val );
else
printf( "\"%s\" is *not* a valid integer string\n" );
}
}