Explain Command line input with example
C lets read arguments from the command line which can then be used in our programs.
We can type arguments after the program name when we run the program.
We have seen this with the compiler for example
c89 -o prog prog.c
c89 is the program, -o prog prog.c the arguments.
In order to be able to use such arguments in our code we must define them as follows:
main(int argc, char **argv)
So our main function now has its own arguments. These are the only arguments main accepts.
• argc is the number of arguments typed -- including the program name.
• argv is an array of strings holding each command line argument -- including the program name in the first array element.
A simple program example:
#include<stdio.h>
main (int argc, char **argv)
{ /* program to print arguments
from command line */
int i;
printf(``argc = %d n n'',argc);
for (i=0;i<argc;++i)
printf(``argv[%d]: %s n'',
i, argv[i]);
}
Assume it is compiled to run it as args.
So if we type:
args f1 ``f2'' f3 4 stop!
The output would be:
argc = 6
argv[0] = args
argv[1] = f1
argv[2] = f2
argv[3] = f3
argv[4] = 4
argv[5] = stop!
NOTE: argv[0] is program name.
argc counts program name
Embedded `` '' are ignored.
Blank spaces delimit end of arguments.
Put blanks in `` '' if needed.