LISTING17.19 Using Command-line Arguments
0: //Listing 17.19 Using Command-line Arguments
1: #include <iostream>
2: int main(int argc, char **argv)
3: {
4: std::cout << “Received “ << argc << “ arguments...\n”;
5: for (int i=0; i<argc; i++)
6: std::cout << “argument “ << i << “: “ << argv[i] << std::endl;
7: return 0;
8: }
TestProgram Teach Yourself C++ In 21 Days
Received 7 arguments...
argumnet 0: TestProgram
argument 1: Teach
argument 2: Yourself
argument 3: C++
argument 4: In
argument 5: 21
argument 6: Days
OUTPUT
632 Day 17
You must either run this code from the command line (that is, from a DOS
box) or you must set the command-line parameters in your compiler (see
your compiler documentation).
NOTE
The function main()declares two arguments:argcis an integer that contains the
count of command-line arguments, and argvis a pointer to the array of strings.
Each string in the array pointed to by argvis a command-line argument. Note that argv
could just as easily have been declared as char *argv[]or char argv[][]. It is a mat-
ter of programming style how you declare argv; even though this program declared it as
a pointer to a pointer, array offsets were still used to access the individual strings.
On line 4,argcis used to print the number of command-line arguments: seven in all,
counting the program name itself.
On lines 5 and 6, each of the command-line arguments is printed, passing the null-termi-
nated strings to coutby indexing into the array of strings.
A more common use of command-line arguments is illustrated by modifying Listing
17.18 to take the filename as a command-line argument, as shown in Listing 17.20.
ANALYSIS