Command Line Arguments
If you are working in a command line environment, it is often helpful to write programs that take arguments from the command line.
• For example, suppose we have a program called sum , which takes two numbers as command line arguments and displays their sum.
We could enter the following command at the operating system prompt: sum 12 16
Because a C++ program starts its execution with function main , command line arguments are passed to main .
Function main can be optionally written with two parameters.
These parameters are traditionally named argc and argv .
The argc parameter is an int , and the argv parameter is an array of char pointers. Here is an example function header for main , using these two parameters:
int main(int argc, char *argv[])
The argc parameter contains the number of items that were typed on the command line, including the name of the program.
The argv parameter is an array whose elements point to C-style strings holding one of the command line arguments.
The the command line sum 12 16
argc = 3
argv[0] = “sum”
argv[1] = “12”
argv[2] = “16”
Example 1
// This program demonstrates how to read command line arguments.
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
cout << "Your line has " << argc << " command line arguments.\n";
cout << "Here they are:\n";
for (int count = 0; count < argc; count++)
cout << argv[count] << endl;
return 0;
}
//output
$ g++ argdemo.cpp -o argdemo
$ ./argdemo 12 34 56
Your line has 4 command line arguments.
Here they are:
./argdemo
12
34
56
$ _
Example 2
// This program takes two command line arguments,
// assumed to be numbers, and displays their sum.
#include <iostream>
#include <cmath> //Needed for atof
uding namespace std;
int main (int argc, char *argv[]) {
double total = 0;
if (argc > 1) {
for (int count = 1; count < argc; count ++)
total += atof (argv[count]);
cout << total << endl;
}
return 0;
}
//output
$ g++ sum.cpp -o sum
$ ./sum 12 16
28
$ ./sum 2 3 5 7 11 13 17
58
$ _
example3
// This program demonstrates the usage
// of command line arguments to open a
// text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
string line;
if (argc > 1) {
ifstream infile(argv[1]);
while(!infile.eof()) {
getline(infile, line);
cout << line << endl;
}
}
else {
cout << "Usage: " << argv[0]
<< " <filename>" << endl;
}
return 0;
}
Last updated
Was this helpful?