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 :

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;

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.

About    Contact    Sitemap    Terms    Privacy