Command Line Arguments in C - C++
Command Line Arguments in C - C++
We can also give command-line arguments in C and C++. Command-line arguments are given after the name of the program in command-line
shell of Operating Systems.
To pass command line arguments, we typically de ne main() with two arguments : rst argument is the number of command line arguments
and second is list of command-line arguments.
or
argc (ARGument Count) is int and stores number of command-line arguments passed by the user including the name of the program. So if
we pass a value to a program, value of argc would be 2 (one for argument and one for program name)
The value of argc should be non negative.
argv(ARGument Vector) is array of character pointers listing all the arguments.
If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain pointers to strings.
Argv[0] is the name of the program , After that till argv[argc-1] every element is command -line arguments.
Input:
Output:
Note : Other platform-dependent formats are also allowed by the C and C++ standards; for example, Unix (though not POSIX.1) and Microsoft
Visual C++ have a third argument giving the program’s environment, otherwise accessible through getenv in stdlib.h: Refer C program to print
environment variables for details.
// C program to illustrate
// command line arguments
#include<stdio.h>
int main(int argc,char* argv[])
{
int counter;
printf("Program Name Is: %s",argv[0]);
if(argc==1)
printf("\nNo Extra Command Line Argument Passed Other Than Program Name");
if(argc>=2)
{
printf("\nNumber Of Arguments Passed: %d",argc);
printf("\n----Following Are The Command Line Arguments Passed----");
for(counter=0;counter<argc;counter++)
printf("\nargv[%d]: %s",counter,argv[counter]);
}
return 0;
}
1. Without argument: When the above code is compiled and executed without passing any argument, it produces following output.
$ ./a.out
Program Name Is: ./a.out
No Extra Command Line Argument Passed Other Than Program Name
2. Three arguments : When the above code is compiled and executed with a three arguments, it produces the following output.
3. Single Argument : When the above code is compiled and executed with a single argument separated by space but inside double quotes, it
produces the following output.
4. Single argument in quotes separated by space : When the above code is compiled and executed with a single argument separated by
space but inside single quotes, it produces the following output.
References:
http://www.cprogramming.com/tutorial/lesson14.html
http://c0x.coding-guidelines.com/5.1.2.2.1.html