Oct 3, 2007

C++ program to demonstrate argc and argv

Every C and C++ program must have a main function. Many times we use this function without parameter (arguments) like main(). This main function also may have two parameters called argc and argv. argc is an integer type parameter and argv is pointer to string *argv[].

We can use this main function with these parameters as shown below

void main(int argc,char *argv[])
{
}

argc parameter counts the number of parameter passed to main function and argv contains actual parameters.

Here is an example to use above concept.

#include<iostream.h>
#include<conio.h>
void main(int argc, char *argv[])
{
clrscr();
cout << argv[1] <<endl; // argv[0] contains program name and argv[1] and onwards contains parameters passed to main
getch();
}

type the above program in c++ editor and save with file name "argdemo" compile the above program make Exe of the program by pressing F9 if you are using Turbo c++ compiler Go to the dosshell by clicking Dos shell option in File menu.

Go to the Source directory where Argedemo.exe is there.
Type argdemo a1 and press Enter key
A1 is a parameter to main function it will be stored in argv[1]
Our program will print argv[1] using cout statment so a1 will get printed on the screen.
Another Example of argc and argv parameters :

#include<iostream.h>
#include<conio.h>
void main(int argc, char * argv[])
{
clrscr();
for (int i=1;i<=argc; i++)
{
cout << argv[i]<<endl;
}
getch();
}


This above program will take parameters when you run .Exe of the program and print all the given parameters using for loop from argv[1] to count of the parameters argc. If you enter four parameters then value of argc would be 4 and for loop execute four times.

C++ program to create a directory on DOS.

#include<iostream.h>
#include<conio.h>
#include<dir.h>
void main(int argc, char *argv[])
{
clrscr();
mkdir (argv[1]);
getch();
}

In the above program mkdir function will create a directory using argv[1] parameter.

C++ program to create multiple DOS directory :

#include<iostream.h>
#include<conio.h>
#include<dir.h>
void main(int argc, char *argv[])
{
clrscr();
for (int i=1;i<=argc; i++)
{
mkdir (argv[i]);
}
getch();
}

Above program can take multiple parameters so that it can create multiple DOS directory using for loop. It will work same as mkdir in Linux / Unix.

Technorati Tags : , , ,

No comments:

Post a Comment