C++ Command line parameters

Command Line Parameters are the ones which are supplied at the beginning of a program. Most of the old day DOS programs will display a list of matching parameters, if the program call is supplied with -help parameter. This -help command will also be a command line parameter for the program instructing it to display the help note.

In C++, the command line parameters are supplied as like other language programs. Internally the two parameters of the c++ main() function will be used to decipher the values. They are named as argc and argv by convention.

The argc is the first parameter of type int. This supplies the number of commands/words that occurred in the program invocation. If the program is called with 2 parameters this will have a value of 3. This includes the program name in addition to the two parameters.
The argv[] is a character array holding each parameter value at one array. Usually the number of the values in this argv[] array is determined using the argc parameter and the values are pulled accordingly.

The following sample shows how to supply parameters to a console c++ program and print them.


#include <iostream.h>

void main(int argc, char *argv[])
{
for(int i=0; i < argc; i++)
cout<<argv[i]<<endl;
}

These command line parameters can be used in any program. Usually console program requiring inputs of server names and other application initialization parameters can be benefited by using these command line parameters.