I need to write a program in a single file "sum.c" that accepts multiple integers on the command line, takes the sum of those integers and prints them to stdout. The program must use something like strtol to convert from string to number.
So far my code looks like this:
#include <stdio.h>
int main (int argc, char *argv[]){
int a, b, sum;
int i; //looping through arguments using i
if (argc<2) {
printf("Please include at least two integers to get the sum.\n");
return -1;
}
a = atoi(argv[1]);
b = atoi(argv[2]);
sum=a+b;
printf(sum);
return (0);
}
This includes an error check to make sure at least two arguments are passed. However my current code only allows for two arguments. I need to figure out how to change this to handle any number of arguments, and to also check that the numbers being passed are ONLY integers and nothing else. I am also still having compilation errors with the original code that I posted here. I have taken a long break from coding so I know it is very poor at the moment.
Updated Code:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
int sum;
sum = 0;
if (argc<2) {
printf("Please include at least two integers to get the
sum.\n");
exit (-1);
}
for (int counter = 1; argv[counter] != NULL; ++counter) {
sum += atoi(argv[counter]);
}
printf("%d\n", sum);
exit (0);
}
How does this look now?
Error I receive when executing:
./sum.c: line 4: syntax error near unexpected token `('
./sum.c: line 4: `int main (int argc, char *argv[]) {'