command line parameters with "-" switch

Hi

I am still learning C++ & I think I am missing something very basic here.
Hope someone can help.

I wrote the below code as a main structure for my C++ code for command line parameters.

This compiles well on UNIX (g++ compiler) and work with 5 & 6 parameters (just added some for tests with white spaces). It also works with "-h", "--h", "--help" etc.

The issue is when I run it (compiled binary), without any parameters, I get "Segmentation Fault (core dumped)".

I am expecting it to return "Usage Display" when no parameters are entered as I think it matches "else" statement.

Any idea/help? What am I missing here?

SRV-A # g++ command-line-with-switches.cc -o command-line-with-switches
SRV-A #
SRV-A # ./command-line-with-switches r r r r r r
This is with 6 parameters
SRV-A # ./command-line-with-switches r r r r r r r
Usage Display
SRV-A # ./command-line-with-switches r r r r r
This is with 5 parameters
SRV-A # ./command-line-with-switches r r r r r
This is with 5 parameters
SRV-A #
SRV-A # ./command-line-with-switches
Segmentation Fault (core dumped)
SRV-A #

Source code:

#include <iostream>
#include <string>

using namespace std;

void usage();

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

if ( (strcmp(argv[1], "-h")==0 || strcmp(argv[1], "-help")==0 || strcmp(argv[1], "--h")==0 || strcmp(argv[1], "--help")==0) && (argc==2) )
{
cout <<"This is for help page"<<endl;
}
else if (argc == 6)
{
cout <<"This is with 5 parameters"<<endl;
}
else if (argc==7)
{
cout <<"This is with 6 parameters"<<endl;
}
else
{
usage();
}
}

void usage()
{
cout <<"Usage Display"<< endl;
}


Mathew
Hi

An **UPDATE

I just got the above working like below but I really would like to know why the above failed at the "else" statement.



#include <iostream>
#include <string>

using namespace std;

void usage();

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

if (argc==2)
{
if ( strcmp(argv[1], "-h")==0 || strcmp(argv[1], "-help")==0 || strcmp(argv[1], "--h")==0 || strcmp(argv[1], "--help")==0)
{
cout <<"This is for help page"<<endl;
}
else
{
usage();
}
}
else if (argc == 6)
{
cout <<"This is with 5 parameters"<<endl;
}
else if (argc==7)
{
cout <<"This is with 6 parameters"<<endl;
}
else
{
usage();
}
}

void usage()
{
cout <<"Usage Display"<< endl;
}


Mathew
The problem is here:
if ( (strcmp(argv[1], "-h")==0 || strcmp(argv[1], "-help")==0 || strcmp(argv[1], "--h")==0 || strcmp(argv[1], "--help")==0) && (argc==2) )

argv array has only one element and you try to read second element from it, which is out of bounds ./ This is undefined behavior, crash in your case. Always check argc first and use a loop.
Topic archived. No new replies allowed.