peterboston peterboston - 14 days ago 6
C++ Question

why my C++ main() doesn't take my parameters

I have a C++ program running in Fedora 20. It can take no parameter or one parameter when I start it via the main(). Now I need more parameters but somehow, it refuse to take the new parameters.

This is how I start it:

$ ./runtest.sh ire 22 33

This is the first line cout inside the main():

UICommTest is starting ... argc=2

I expect the argc=4.

This is my main():

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

std::cout << "UICommTest is starting ... argc="<< argc << std::endl;

if(argc == 1)
{
UICommTest::startTest(false);
}
else if(argc == 2)
{
if(string(argv[1]) == "true")
{
UICommTest::startTest(true);
}
else if(string(argv[1]) == "ire")
{
UICommTest::startTestIRE("-1", "-1");
}
else
{
std::cout << "Usage:: ..." << std::endl;
}
}
else if(argc == 4)
{
if(string(argv[1]) == "ire")
{
UICommTest::startTestIRE(argv[2], argv[3]);
}
else
{
std::cout << "Usage:: ..." << std::endl;
}
}
else
{
std::cout << "Usage:: ..." << std::endl;
}

return EXIT_SUCCESS;
}


I do clean and make several times. And I am sure the new changes are in. Anybody can help about this?

Answer

So you have a shell script runtest.sh, it seems. In it you probably have a line like this (path may be something longer than just ./):

./UICommTest "$1" "$2"

It should be apparent that this will give your program only 2 arguments. Change that line to this:

./UICommTest "$@"

Note: Using the "$@" is important detail, it has the special feature, that it expands to equivalent of "$1" "$2" "$3" .... The quotes are important, so that if you pass a parameter with spaces, it still remains as one parameter.

Comments