Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Streams 631

17


On lines 5–20, a stripped-down Animalclass is declared. On lines 24–34, a file is
created and opened for output in binary mode. An animal whose weight is 50 and
who is 100 days old is created on line 36, and its data is written to the file on line 37.
The file is closed on line 39 and reopened for reading in binary mode on line 41. A sec-
ond animal is created, on line 48, whose weight is 1 and who is only one day old. The
data from the file is read into the new animal object on line 53, wiping out the existing
data and replacing it with the data from the file. The output confirms this.

Command-line Processing ..................................................................................


Many operating systems, such as DOS and Unix, enable the user to pass parameters to
your program when the program starts. These are called command-line options and are
typically separated by spaces on the command line. For example,
SomeProgram Param1 Param2 Param3
These parameters are not passed to main()directly. Instead, every program’s main()
function is passed two parameters. The first is an integer count of the number of argu-
ments on the command line. The program name itself is counted, so every program has
at least one parameter. The sample command line shown previously has four. (The name
SomeProgramplus the three parameters make a total of four command-line arguments.)
The second parameter passed to main()is an array of pointers to character strings.
Because an array name is a constant pointer to the first element of the array, you can
declare this argument to be a pointer to a pointer to char, a pointer to an array of char,
or an array of arrays of char.
Typically, the first argument is called argc(argument count), but you can call it anything
you like. The second argument is often called argv(argument vector), but again this is
just a convention.
It is common to test argcto ensure you’ve received the expected number of arguments
and to use argvto access the strings themselves. Note that argv[0]is the name of the
program, and argv[1]is the first parameter to the program, represented as a string. If
your program takes two numbers as arguments, you need to translate these numbers to
strings. On Day 21, you will see how to use the Standard Library conversions. Listing
17.19 illustrates how to use the command-line arguments.

ANALYSIS
Free download pdf