Reputation: 312
I have the next code :
#include "CmdLine.h"
void main(int argc, TCHAR **argv)
{
CCmdLine cmdLine;
// parse argc,argv
if (cmdLine.SplitLine(argc, argv) < 1)
{
// no switches were given on the command line, abort
ASSERT(0);
exit(-1);
}
// test for the 'help' case
if (cmdLine.HasSwitch("-h"))
{
show_help();
exit(0);
}
// get the required arguments
StringType p1_1, p1_2, p2_1;
try
{
// if any of these fail, we'll end up in the catch() block
p1_1 = cmdLine.GetArgument("-p1", 0);
p1_2 = cmdLine.GetArgument("-p1", 1);
p2_1 = cmdLine.GetArgument("-p2", 0);
}
catch (...)
{
// one of the required arguments was missing, abort
ASSERT(0);
exit(-1);
}
// get the optional parameters
// convert to an int, default to '100'
int iOpt1Val = atoi(cmdLine.GetSafeArgument("-opt1", 0, 100));
// since opt2 has no arguments, just test for the presence of
// the '-opt2' switch
bool bOptVal2 = cmdLine.HasSwitch("-opt2");
.... and so on....
}
I have the CCmdLine class implemented and this main is an exemple of how to use it . I am having difficulties understanding how i get input values . I have tried to read them with scanf from the console but the argc won't increment and results faulty reading.
I am a beginner in c++ and i would like to know who to make this code work .
Thanks .
Upvotes: 0
Views: 733
Reputation: 29966
Argc
and argv
only contain the arguments that were passed when the program started. So if you execute it with myapp.exe option1 option2 option3
, than in your argv
you will have:
//<--argv[0]
//<--argv[1]
//<--argv[2]
//<--argv[3]
In a nutshell, when a program starts, the arguments to main are initialized to meet the following conditions:
argc
is greater than zero.argv[argc]
is a null pointer.argv[0]
through to argv[argc-1]
are pointers to strings representing the actual arguments.argv[0]
will be a string containing the program's name or a null string if that is not available. Remaining elements of argv
represent the arguments supplied to the program. You can find some more information for example here.
All attempts to read input later (either with cin
, scanf
or whatever else) will not save the inputed values to argv
, you will need to handle the input yourself.
Upvotes: 1
Reputation: 5546
This is quite easy:
void main(int argc, char **argv)
{
std::string arg1(argv[0]);
std::string arg2(argv[1]);
}
Upvotes: 0
Reputation: 17655
pass the input values from commandline while run the programs e.g
program_name.exe arg1 arg2
Upvotes: 0