C/C++ Arena

Step 5 of 6

Command-line arguments

main can receive the words typed after the program name:

int main(int argc, char **argv)

So ./sum 4 5 6 has argc == 4 and argv[2] is "5". Convert numbers with strtol, which also tells you where parsing stopped, so you can detect junk like "12abc":

char *end;
long v = strtol(argv[i], &end, 10);
if (*end != '\0' || end == argv[i]) { /* not a clean number */ }

Your turn: print the sum of all arguments. If any argument isn't a clean integer, print bad number: ARG and stop. The tests run your program with different arguments.

Previous: const-correct interfaces Next: Challenge: a real command-line tool