Command Line Arguments in C++

The main fuction in a C++ program can either be defined as:


The second variation allows you to specify command line arguments to be passed to your main function. You may have as many command line arguments as you like. The number of arguments is stored in argc and argv is a array of points to strings which represent the parameters that you passed in to main. Argc is always at least equal to 1 because argv[0] is the name of your program. So if your program is called sort and you typed "sort file1 file2", the following parameters to main are set: argc = 3, argv[0] = sort, argv[1] = file1, and argv[2] = file2.

To demonstrate, write the following code:
Compile this a run "a.out param1 param2 param3" and the arguments will be printed.

Argc tells you how many command line parameters were passed in. You use this parameter to error check the usage of your program to make sure the exact number of expected parameters were passed to the main program. You should always error check the number of command line parameters and if the user does not enter the EXACT number of expected command line parameters, you should print a message stating the expected usage of the program and then exit. I always like to make my usage message match that of a typical unix usage message. To see what I mean, type the command grep at the command prompt in a Unix shell with no command line parameters. You get an expected usage message. It then tells you to type "grep --help" for info on the actual parameters. I don't expect you to do all of this for your assignments but you should at the very least error check argc and print out a usage message. The help menu is something that you should be doing but is not required.