Reputation: 73
I need to accept an array of integers from the command line, such as: ./test 2 9 -5 17
Currently I have:
int main(int argc, int *argv[])
And then loops to find the two numbers within this array that create the maximum value possible starting with argv[1]. Obviously this does not work. Do I need it to be:
int main(int argc, char *argv[])
and then parse this? I am not sure how to covert characters to integers in C.
Thanks,
Upvotes: 0
Views: 950
Reputation: 11237
int main(int argc, char *argv[])
{
size_t i;
int n;
for (i = 0; i < argc; ++i) {
if (sscanf(argv[i], "%d", &n) == 0) {
fprintf(stderr, "Position %d is not an int\n", i + 1);
return 1;
}
printf("%d\n", n);
}
return 0;
}
Upvotes: 0
Reputation: 4084
Use strtol() to convert each argv[i] (for i starting at 1) to a long int.
Upvotes: 1