CS202 Computer Science II
FAQ Newsboard  Telnet Email TA Lectures Assignments Man pages Help

Command line arguments : getting started

To take command line arguments, the C++ ``main'' procedure needs to be declared a particular way. For example the following program prints its arguments:

#include <iostream.h>

int main(int argc, char *argv[])
{
  int i;
  
  for(i = 1; i < argc; i++){
    cout << argv[i]  << " " ;

  }
  cout << endl;
}

main's first argument (traditionally called argc for argument count) is the number of command-line arguments the program was invoked with. The second (called argv, for argument vector) is a pointer to an array of character strings that contain the arguments, one per string. If the program above was in a file called mirror.c, then

% g++ -o mirror mirror.cpp 
% mirror hello world
prints the output

hello world
% mirror there was a house in new orleans
would print
there was a house in new orleans
By convention argv[0] is the name by which the program was invoked, so argc is at least 1. In the first example above argc is 3, and argv[0] is "mirror", argv[1] is "hello" and argv[2] is "world." argv[argc] is a null pointer.

argc and argv are setup and initialized by the operating system. argc is an integer (we all know about integers). argv is more interesting -- I have declared it using char * argv[], which may seem a little strange. For example, what does the * mean? Don't worry about it till we talk about pointers.

Right now, all you need to know is that argv is an array of strings. Since a string is an array of characters ending in '\0', argv, an array of strings, is a two dimensional array of characters. A picture may help:
shows the argv two dimensional array for

mirror hello world
Although rows may be of different length, argv is still a kind of two dimensional array in C++.

Consider the second example:

% mirror there is a house in new orleans
argc is 8. argv[0] is the character array that contains the program name: "mirror". The operating system always ensures that argv[0] contains the name of the program. argv[1] is the character array or string that contains the first argument to the program: "there". argv[2] is then "is", argv[3] is "a", argv[4] is "house", and so on. argv[8] or argv[argc] is the empty string.

Using this way of accessing command line arguments allows you to dispense with providing users menus or asking for input. Unix programs (usually) have a default behavior, that can be modified using command line options. We will, in future, try and follow this convention. After all, we can always read the man page to find out how to use a program.

Here's another way to write mirror, outputting one character at a time. The two-dimensional nature of the argv[][] array is apparent in this implementation.