/* Name: improved-ex13-5.c Purpose: finds the sum of all command line arguments Author: Bill Slough Notes: 1. Uses strtol(), the preferred approach to convert strings to integer values. 2. Note that the sum is now accumulated using the long data type. */ #include #include #include #include #define BASE 10 /* assume command line arguments to be base 10 */ bool bad_arg = false; /* has at least one bad argument been seen? */ void process(long *psum, const char *arg); int main(int argc, char *argv[ ]) { int i; long sum; /* process each command line argument, skipping the 0th argument */ i = 1; sum = 0; while (argv[i] != NULL) { process(&sum, argv[i]); i++; } /* announce result */ if (!bad_arg) { printf("sum = %ld\n", sum); return 0; } else { printf("Errors: no reliable sum available.\n"); return 1; } } void process(long *psum, const char *arg) { char *ptr; /* convert this argument and accumulate the sum */ *psum += strtol(arg, &ptr, BASE); /* did an error occur during conversion? */ if (*ptr != '\0' || errno == EINVAL || errno == ERANGE) { printf("error in command line argument: \"%s\"\n", arg); bad_arg = true; } }