Question

I'm C++ programming in a linux environment and I'm trying to parse command line arguments using getopt. I want to require an input -s OR -q (longforms --stack and --queue respectively), not both, as well as an input -o with a required argument:

int opt = 0, index = 0, stack=-1, map=-1;
while((opt = getopt_long (argc, argv, ":sqho:", longOpts, &index)) != -1){
    cout<<opt;

    switch(opt) {
        case 's':
            stack=0;
            cout << "Stack"<<stack<<"\n";
            break;
        case 'q':
            stack=1;
            cout << "Queue"<<stack<<"\n";
            //optarg is defined in getopt.h
            break;
        case 'h':
            cout<< "To run this program, use one of the valid cmd line args (longforms: stack, queue, help, output (M|L); shortforms: s, q, h, o (M|L), respectiely) \naccompanied with appropriate file redirection";
            exit(0);
            break;
        case 'o':
            //opt is 'M' or 'L'
            cout<<"output method is: "<<optarg<<"\n";
            if(*optarg=='M') map=1;
            else if(*optarg=='L') map=0;
            else map=-1;
            cout<<map<<"\n";
        case ':':
            cerr<<"Map or list output must be specified as an argument to -o: "<<opt<<"\n"; 
        case '?':

            cerr << "Command line error. one or more flags not recognized: " <<opt<<"\n";
            //exit(1);
            break;
    }

}
for(int i=1; i<argc; i++){
    cout<<*argv[i]<<endl;
}
return 0;

}

This contains the proper #includes at the top, and compiles fine.

However, when I try to run ./hunt -q -o M, cases 'q', 'o', ':', and '?' all execute. I decided to output whatever character was triggering the ':' and '?' blocks, and the console displays 111, the ASCII value of the character 'o'.

This is extremely confusing to me, since after getopt triggers the 'o' block, shouldn't it then return -1 signifying there are no more command line arguments? I would appreciate any help/suggestions. Thanks!

Était-ce utile?

La solution

You are missing a break in case 'o' and case ':'.

This causes a fall through from o to : to ?.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top