|

The
command line can be used to
pass arguments to a program when starting it. The main()
function of every
program can be passed two arguments:
Argument 1 - (arg c) integer count of the number of arguments on
the command line.
Argument 2 - (arg v) an array of pointers to character strings.
In the case of argument 1, the program name itself counts as an
argument, so there is always at least one argument.
The first argument is most often called "arg c" for argument
count, and the second argument is most often called "arg v" for
argument vector. In the case of the character array,
argv[0] would be the name of the program, an so argv[1] would be
the first argument. Example:
#include
<iostream>
int main(int
argc, char **argv)
{
std::cout << "I received " << argc << " arguments!\n";
for(int i=0; i<argc; i++)
std::cout << "Argument: " << i << ":
" << argv[i] << std::endl;
return 0;
} |
The example above will
simply display each element in the argv[] array one by one.
So, if five arguments were passed in, all five would be
displayed as the loop iterates through each element in argv[i].
Below is another example of passing in parameters to the command
line when executing an application.
#include <fstream>
#include <iostream>
using namespace std;
class Monster
{
public:
Monster(int
Strength, long points):itsStrength(Strength),HitPoints(points){ }
~Monster(){}
int
GetStrength() const {
return itsStrength; }
void SetStrength(int
Strength) { itsStrength = Strength; }
long
GetHitPoints() const {
return HitPoints; }
void SetHitPoints(long
points) { HitPoints = points; }
private:
int
itsStrength;
long
HitPoints;
};
int main(int argc,
char *argv[])
// returns 1 on
error
{
//If
argument count is not at least 2, that is the
program name and a monster name. display syntax
if(argc != 2)
{
cout << "Usage: " << argv[0] << " <FileName>" <<
endl;
return(1);
}
//Create a file for output using the name passed in
as a parameter
ofstream OutputFile(argv[1],ios::binary);
if(!OutputFile)
{
cout << "Unable to open " << argv[1] << " for
writing.\n";
return(1);
}
Monster Mothra(50,100);
OutputFile.write((char*) &Mothra, sizeof Mothra);
OutputFile.close();
//Open a file for input using the name passed in as
a parameter
ifstream InputFile(argv[1],ios::binary);
if(!InputFile)
{
cout << "Unable to open " << argv[1] << " for
reading.\n";
return(1);
}
Monster MothraTwo(1,1);
cout << "MothraTwo Strength: " <<
MothraTwo.GetStrength() <<
endl;
cout << "MothraTwo points: " <<
MothraTwo.GetHitPoints()
<< endl;
InputFile.read((char*) &MothraTwo, sizeof MothraTwo);
cout << "MothraTwo Strength: " <<
MothraTwo.GetStrength() <<
endl;
cout << "MothraTwo points: " <<
MothraTwo.GetHitPoints()
<< endl;
InputFile.close();
return 0;
}
|
©2004 C. Germany
|