Command Line Arguments in C++

In C++ it is possible to accept command-line arguments.

To pass command-line arguments into your program, C++ have a special argument list for main( ), which looks like this:

int main(int argc, char* argv[]) {
   ...
}

The first argument (argc) is the number of elements in the array, which is the second argument (argv). The second argument is always an array of char*, because the arguments are passed from the command line as character arrays (an array can be passed only as a pointer). Each whitespace-delimited cluster of characters on the command line is turned into a separate array argument. The following program (download) prints out all its command-line arguments by stepping through the array:

#include <iostream>
using namespace std;

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

You’ll notice that argv[0] is the path and name of the program itself. This allows the program to discover information about itself. It also adds one more to the array of program arguments, so a common error when fetching command-line arguments is to grab argv[0] when you want argv[1].

You are not forced to use argc and argv as identifiers in main( ), those identifiers are only conventions (but it will confuse people if you don’t use them). Also, there is an alternate way to declare argv:

int main(int argc, char** argv) {
   ...
}

Both forms are equivalent.

All you get from the command-line is character arrays; if you want to treat an argument as some other type, you are responsible for converting it inside your program. To facilitate the conversion to numbers, there are some helper functions in the Standard C library, declared in <cstdlib>. The simplest ones to use are atoi( ), atol( ), and atof( ) to convert an ASCII character array to an int, long, and double, respectively. Here’s an example using atoi( ) (the other two functions are called the same way):

#include <iostream>
#include <cstdlib>
using namespace std;

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

In this program, you can put any number of arguments on the command line. You’ll notice that the for loop starts at the value 1 to skip over the program name at argv[0]. Also, if you put a floating-point number containing a decimal point on the command line, atoi( ) takes only the digits up to the decimal point. If you put non-numbers on the command line, these come back from atoi( ) as zero.