C++ Command Line Arguments:
When a program in C++ is compiled an executable file is created. This executable file can he used to execute the program directly from the DOS prompt. The arguments can also he passed to the program from the DOS prompt during execution of the program.
The arguments that are passed to a function at the DOS prompt are called command line arguments.
For example in MSDOS to copy a file from one location to another location, two arguments (i.e., source file name and other for target file name), are provided to the copy command. These are called command line arguments. In C++, arguments can also he given in the main function. These arguments arc given as command line arguments when the program is executed from the DOS prompt.
The program example given below explains the concept of command line arguments.
Program:
#include <iostream.h>
#include <string.h>
main (int ca, char *st[ ] )
{
char cp[15];
strcpy (cp. st [1] )
cout<<cp;
}
In the above program, two arguments have been used in the main ( ) function. The first argument is used by the program to count the number of command line arguments. It must he given as arguments and it is always of int type. The second argument is an array of string. The arguments passing from the DOS prompt with the program are stored in this array. The program tile name with its path is stored in the first clement of array and the first parameter passed with the program is stored in the second element of array.
Suppose the above program is compiled and is named “test” as filename. The program is executed from the DOS prompt as:
The word “Canada” is stored in second element of “st”, i.e st [1] as argument. The contents of st [1] are copied to string variable “cp” within the program and then printed on the screen. In the first element of “st” array, i.e. st [0], the pathname of the program tile is stored. It must be noted that to pass more than one argument, each argument is given, separated by blank space.
comment closed