The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

Command Line Arguments

We know that every C++ program has atleast one function i.e main( ). Similar to other functions, main( ) can also take arguments. These arguments are known as command line arguments and they are passed to the program at runtime. main( ) actually takes two arguments :
int argc is the argument count i.e the number of arguments passed to the program.
char *argv[ ] is an array of strings where each string is a command line argument. The first string i.e argv[0] is the name of the program. Thus, there is atleast one argument always passed to main.
Following program illustrates the use of command line arguments :

#include<iostream>
using namespace std;

/* main
 * params : argc ( No. of command line arguments )
 * argv[] : array of strings ( arguments )
 */
int main(int argc, char *argv[]) {
   cout << "No. of arguments : " << argc << endl;
   int i;
   for ( i = 0; i < argc; i++ ) {
      cout << "argv[" << i << "] = " << argv[i] << endl;
   }
   return 0;
}
Run this program in your system to take command line arguments  

Assuming we are on linux system and the program is saved as prog.cpp
Compile : g++ -o prog prog.cpp
Executable is generated with name prog
Run : ./prog Hello World
where the command line arguments are " ./prog " , " Hello " and " World "
Output :
No. of arguments : 3
argv[0] = ./prog
argv[1] = Hello
argv[2] = World
On a windows system, if you are using some IDEs, there will be some option to input command line arguments.

Back | Next