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".