logo

Command Line Arguments

Reference: Deitel section 18.4

The following program shows how to capture command line arguments within a C++ program.

   int main (int argc, char *argv[])
   {
      cout << "The command is " << argv[0] << endl;

      for (int index = 1; index < argc; index ++) {
         cout << " Next Arg is " << argv[index];
      }
      cout <<endl;
      return 0;
   }

Suppose that this program is executed with the following command:

   a.out Cathy 20 "John Doe"

The arguments to the function called main are used to refer to command line arguments. The argc integer tells how many arguments there are, where the command name (here a.out) is counted as one of the arguments. For this example, argc will be 4. Argument argv[0] is the command itself, argv[1] is the first argument ("Cathy"), etc. When the program starts up, the compiler stores 4 in argc, while argv[0] is a pointer to the string a.out, argv[1] is a pointer to the string Cathy, argv[2] is a pointer to the string 20, and argv[3] is a pointer to the string John Doe. Since John Doe appears in quotes on the command line it is treated as a single argument instead of two arguments.

This is the output that would be generated by the program:

   The command is a.out
    Next Arg is Cathy Next Arg is 20 Next Arg is John Doe

All of the arguments are returned as character strings. If you want the integer value of one of the arguments, such as the number 20 in our example, you would store the correct value into integer variable intArgument with the statement

   intArgument = atoi(argv[2]);

To use atoi, you must include the header file <stdlib.h>or <cstdlib>.</cstdlib></stdlib.h>