Command Line Parameters in C++

Here is a brief tutorial on how to add command-line parameters in C++:

The function main can be used with two parameters argc and argv as follows:

int main(int argc, char *argv[])

The value of argc is the number of arguments on the command line including the name of the program itself.  For example, the command line "a.out file1.txt file2.txt" would set argc to 3.  If your program requires three command line arguments, then argc must be 4.  For usability purposes, your program should detect invalid command lines and exit with an appropriate error message that indicates how to specify the command line parameters.

The variable argv is an array of C-style strings (an array of characters).  Each element of the array is holding one command line argument.  argv[0] always contains the name of the program, argv[1] holds the first command line argument, and so forth.  The size of the argv array is always equal to argc. For example, in the command line "a.out file1.txt file2.txt", argv[0] is "a.out", argv[1] is "file1.txt", and argv[2] is "file2.txt".


This is a personal WEB site developed and maintained by an individual and not by Seattle University. The content and link(s) provided on this site do not represent or reflect the view(s) of Seattle University. The individual who authored this site is solely responsible for the site's content. This site and its author are subject to applicable University policies including the Computer Acceptable Use Policy (www.seattleu.edu/policies).