CSC 209 lab 10 solutions, week of 19 July 2022
Question 8:
Problem:
"./a.out num1 num2" outputs the sum of the two numbers.
Code:
int main(int argc, char **argv)
{
if (argv[2] == NULL) {
printf("two integers required on the command line");
return(55);
}
printf("%d", atoi(argv[1]) + atoi(argv[2]));
}
Solution:
int main(int argc, char **argv)
{
if (argc != 3) {
fprintf(stderr, "usage: %s num1 num2\n", argv[0]);
return(1);
}
printf("%d\n", atoi(argv[1]) + atoi(argv[2]));
return(0);
}
Problems fixed above:
- The original check for argument count is bogus.
- That error message is actually a complaint about the usage, so it should
be formulated as a standard usage error. Also, it was missing a newline.
- Errors go to stderr, not stdout.
- There's no reason for an error exit status of 55; avoid random numbers
like this. If we have no particular reason to distinguish this error exit
status, we use 1.
- Missing newline in successful printf().
- Missing return statement means that main() returns a somewhat random
value in the success case. At the end of main() above we have a successful execution, so the return
value, and hence the process exit status, should be zero.
[press 'back' in your web browser to return to the problems]