CS157 CLA
% c11 -o getAvg getAvg.c % ./getAvg 98 95 89 90 92 83 The average is 91.2 % ./getAvg 91.2 77 90 68 91 The average is 81.5
ls -l foo
#include <stdio.h> int main(int argc, char *argv[ ]) { return 0; }
main()
argc
(number of arguments)
argv
(array of arguments)
argv[0]
#include <stdio.h> int main(int argc, char *argv[]) { printf("The %d args are:\n", argc); for (int i=0; i<argc; i++) printf("%d\t%s\n", i, argv[i]); return 0; }
% ./a.out The 1 arguments are: 0 a.out % a.out 98 Cookie Monster rules The 5 arguments are: 0 a.out 1 98 2 Cookie 3 Monster 4 rules
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int sum=0; for (int i=1; i<argc; i++) sum += atoi(argv[i]); printf("The average is: %f\n", sum / (argc - 1.0)); return 0; }
% gcc -o getAvg getAvg.c % ./getAvg 98 95 89 90 92 83 The average is: 91.166667 % ./getAvg 77 90 68 91 The average is: 81.500000
#include <stdio.h> int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s <minimum> <maximum>\n", argv[0]); return 1; } // your code here return 0; }
strcmp
for each expected argument
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char *argv[]) { for (int i=1; i<argc; i++) { if (strcmp(argv[i], "-h") == 0) // do stuff for -h option printf("Help is on its way!\n"); else if (strcmp(argv[i], "-n") == 0) { // now we know the next cmd-line arg is our number int num = atoi(argv[++i]); printf("Your lucky number is %d\n", num); } else { fprintf(stderr, "Unknown option \"%s\".\n", argv[i]); return 2; } } return 0; }