Programs that have minimal and/or optional inputs, command line arguments offer a great way to make programs more modular. Command line arguments are optional string arguments that a user can give to a program upon execution. These arguments are passed by the operating system to the program, and the program can use them as input.
For example
Let’s write a short program to print the value of all the command line parameters:
#include <iostream>
int main(int argc, char *argv[])
{
using namespace std;
cout << "There are " << argc << " arguments:" << endl;
// Loop through each argument and print its number and value
for (int nArg=0; nArg < argc; nArg++)
cout << nArg << " " << argv[nArg] << endl;
return 0;
}
Now, when we invoke this program with the command line arguments “Myfile.txt” and “100″, the output will be as follows:
There are 3 arguments:
0 C:\\WordCount
1 Myfile.txt
2 100
Argument 0 is always the name of the current program being run. Argument 1 and 2 in this case are the two command line parameters we passed in.
For example
Let’s write a short program to print the value of all the command line parameters:
#include <iostream>
int main(int argc, char *argv[])
{
using namespace std;
cout << "There are " << argc << " arguments:" << endl;
// Loop through each argument and print its number and value
for (int nArg=0; nArg < argc; nArg++)
cout << nArg << " " << argv[nArg] << endl;
return 0;
}
Now, when we invoke this program with the command line arguments “Myfile.txt” and “100″, the output will be as follows:
There are 3 arguments:
0 C:\\WordCount
1 Myfile.txt
2 100
Argument 0 is always the name of the current program being run. Argument 1 and 2 in this case are the two command line parameters we passed in.