If you're passing an integer through argv
, why wouldn't you use atoi
? All you have to do is validate your parameters to verify you actually did pass enough arguments in.
The atoi
function takes in a const char*
argument and returns an int
, which sounds exactly like what you're looking for.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc > 1) {
for (int i = 1; i < argc; ++i) {
printf("Digit: %d\n", atoi(argv[i]));
}
}
return EXIT_SUCCESS;
}
Input:
./a.out 1 a 4 hello 72
Output:
Digit: 1
Digit: 0
Digit: 4
Digit: 0
Digit: 72
Update: Upon further research, strtol
is the function you need. atoi
does no error checking, and the C standard says nothing regarding what happens when atoi
returns an error, so the function isn't considered safe, so while I initially thought the function was returning zero, it was actually returning an error.
If you have access to strtonum
, that function is very reliable from what I've seen. I don't have access to it myself, since it seems to only be available on FreeBSD.
If you don't have access to that though, strtol
is the way to go. It takes a const char*
as input, so it does accept the right input for what you're looking for, as well as an end pointer and a base, and in addition it legitimately returns 0 on both successes and failure. It's at least going to be safer than using atoi
.