command-line arguments
command-line arguments allow users to pass information to a program at runtime via the command
line. These arguments are passed to the program's main function as parameters.
The main function in C++ can take the following form to handle command-line arguments:
Syntax
int main(int argc, char* argv[]) {
// Your code here
}
Parameters
argc (argument count):
An integer that holds the number of command-line arguments passed to the program.
Includes the name of the program as the first argument, so argc is always at least 1.
argv (argument vector):
An array of C-style strings (char*) representing the arguments.
argv[0] contains the name or path of the program.
argv[1] to argv[argc - 1] contain the additional arguments.
Example Program
Here is an example that demonstrates command-line arguments:
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
cout << "Number of arguments: " << argc << endl;
for (int i = 0; i < argc; i++) {
cout << "Argument " << i << ": " << argv[i] << endl;
}
return 0;
}