You could also use strtol
(if the input is supposed to be an integer, anyway):
#include <errno.h>
...
char *chk = NULL;
errno = 0;
long val = strtol( arguments[1], &chk, 0 );
if ( !isspace( *chk ) && *chk != 0 )
{
fprintf( stderr, "%s is not a valid integer string!\n", arguments[1] );
}
else
{
if ( errno == ERANGE )
{
fprintf( stderr, "%s cannot be represented as a long\n" );
}
else
{
// arguments[1] is a valid integer string
do_something_with( val );
}
}
strtol
takes the input string and attempts to convert it to the corresponding integer value (result is a long
). chk
will point to the first character in the string that is not part of a valid integer string; if this character is not whitespace or 0, then the input was not a properly formed integer string. The last argument 0
indicates that the input string can be in either hex, decimal, or octal formats, and will be converted appropriately. If you want to limit valid inputs to decimal format, use 10
.