You should not be using function atoi
. If fact, you should forget it ever existed. It has no practical uses.
While Jack's answer is correct in stating that the argv
strings have to be converted to numbers first, using atoi
for that purpose (specifically in the situation when the input comes from the "outside world") is a crime against C programming. There are virtually no situations when atoi
can be meaningfully used in a program.
The function that you should be using in this case is strtol
char *end;
long long_value = strtol(argv[2], &end, 10);
if (*end != '\0' || errno == ERANGE)
/* Conversion error happened */;
The exact error checking condition (like whether to require *end == '\0'
) will actually depend on your intent.
If you want to obtain an int
in the end, you should also check the value for int
range (or for your application-specific range)
if (long_value < INT_MIN || long_value > INT_MAX)
/* Out of bounds error */;
int value = long_value;
/* This is your final value */