CS16, 10W, Handout to go with H07 (command line arguments) (printable PDF)

Available online at: http://www.cs.ucsb.edu/~pconrad/cs16/10W/homework/H07/handout

The assignment is available at http://www.cs.ucsb.edu/~pconrad/cs16/10W/homework/H07


This handout is your reading assignment to go with H07—this material is not covered in the textbook.
This is a review of some material covered in lecture on 01/21, and in lab03.


Command line arguments:

Command line arguments allow us to provide input to a C program through the command line.

For example, instead of typing

./gameScore

to run the program foo.c, we type:

./gameScore Steelers 30 Dolphins 20

and the values "Steelers" "30" "Dolphins" and "20" will be available inside the C program—we don't have to use scanf to prompt for them.

Here's how it works:

Please turn over for more


Continued from other side

Double Subscripting

Working again with the command line:
./gameScore Steelers 30 Dolphins 20

we see that argv[1] has the value "Steelers", and argv[3] has the value "Dolphins".

We can double subscript these, because argv[1], as a string, is an array of characters followed by a null character.

That is, argv[1][0] is the character 'S', argv[1][1] is 't', argv[1][2] is 'e', etc.

The full string is shown in this table:

argv[1][0] argv[1][1] argv[1][2] argv[1][3] argv[1][4] argv[1][5] argv[1][6] argv[1][7] argv[1][8] argv[1][9]
'S' 't' 'e' 'e' 'l' 'e' 'r' 's' '\0' invalid
subscript

Similarly for argv[2], which is "30", we have:

argv[2][0] argv[2][1] argv[2][2] argv[2][3]
'3' '0' '\0' invalid
subscript

Converting to integer

To convert to integer, we use the function atoi() as shown below.

For example:

int width, height;
if (argv!=2)
{ printf("Usage: ./makeBox width height\n");
return 1;
}
width=atoi(argv[1]);
height=atoi(argv[2]);

Converting to double (floating point numbers)

Converting to double works the same as integers, but we use atof instead of atoi.


End of H07 handout