Command Line Arguments in C++
Command-line arguments are a common way to parameterize execution of programs. For example, ./program arg1 arg2
passes arg1
and arg2
as arguments to the program.
To experiment with command-line arguments, it’s best to compile the program first.
In C++, command-line arguments are passed to the main
function through the argc
(argument count) and argv
(argument vector) parameters. argc
is an integer that represents the number of arguments, and argv
is an array of C-style strings (char*) containing the arguments.
The first element of argv
(index 0) is always the name of the program itself. The actual command-line arguments start from index 1.
In this example, we use C++ standard library containers and algorithms to handle the arguments more easily:
- We create a
vector<string>
calledargsWithProg
that includes all arguments, including the program name. - We create another
vector<string>
calledargsWithoutProg
that includes only the command-line arguments, excluding the program name. - We demonstrate how to access an individual argument by index.
- We print all the arguments to show how they can be accessed and manipulated.
This approach provides a more C++-idiomatic way of handling command-line arguments compared to directly using argc
and argv
.
Next, we’ll look at more advanced command-line processing with option parsing libraries in C++.