How to Pass Command Line Arguments to your C++ Code
If you have noticed the definition of your main method in your C++ program, sometimes it shows two input parameters, one int type variable “argc” and another pointer to a character array “argv[]”. These are basically called the command line arguments that are passed to any C++ code. Command line arguments are passed whenever we run an executable of any C++ code. They are very useful in cases where you want an initial input from the user before actually starting the code. They are used to create generic programs as well and their behaviour varies depending on the basis of the command line input. Following step by step guide is to elaborate the use of command line arguments in C++.
Instructions
-
1
First of all you need to know what actually is argc and argv[] in “int main(int argc, char *argv[]);”. Argc represents the number of command line parameters passed to the main and argv[] is the array that contains the command line arguments passed.
-
2
As an example if you want to execute the executable of your code and you do it like “-a –b myexecutable.exe” then the value of argc will be 3 and argv[0] will have myexecutable.exe, argv[1] will contain “-a” and argv[2] will contain “-b”.
-
3
As an example, consider a file executed using “-a –b mycode.exe”, mycode.exe represents the following main method.
int main(int argc, char *argv[]);
{
for(int k=1; k< argc; k++)
cout<< k
}
}
The output of this code will be
-a
-b
Note: that –a and –b were passed as command line arguments and they are stored in argv[]. So we used a loop counting on argc that is size of argv[]. This is how we access the command line arguments.