Activity - Command-Line Arguments
- Obtain a copy of the template C program, atoi-template.c:
cd ~/cs50
cp /thayerfs/courses/22spring/cosc050/workspace/atoi-template.c atoi.c
- Study the loop. What is the first value of
i
? what is the last value ofi
? why?
Because C arrays are indexed from zero, and the first element
argv[0]
is the command name; thus there areargc-1
arguments and the first argument isargv[1]
and the last argument isargv[argc-1]
.
- Fill in the loop body so it attempts to extract an integer from each argument, and prints one line for each argument. For example:
$ ./atoi 42 -12 0 x -y 123x "4 5" "42 "
argument 1: 42
argument 2: -12
argument 3: 0
argument 4: 'x' is not a valid integer
argument 5: '-y' is not a valid integer
argument 6: '123x' is not a valid integer
argument 7: '4 5' is not a valid integer
argument 8: '42 ' is not a valid integer
- Solution: atoi.c