getopt:不识别有效的命令行参数

时间:2014-01-26 00:34:46

标签: c++ getopt getopt-long

我是Linux环境下的C ++编程,我正在尝试使用getopt解析命令行参数。我想要输入-s OR -q(longforms --stack和--queue),而不是两者,以及带有必需参数的输入-o:

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;

}

这包含顶部正确的#includes,编译得很好。

然而,当我尝试运行./hunt -q -o M时,案例'q','o',':'和'?'全部执行。我决定输出触发':'和'?'的任何字符。块,控制台显示111,字符“o”的ASCII值。

这对我来说非常困惑,因为在getopt触发'o'块后,它不应该返回-1表示没有更多的命令行参数吗?我将不胜感激任何帮助/建议。谢谢!

1 个答案:

答案 0 :(得分:0)

您错过了breakcase 'o'中的case ':'

这会导致从o:的下降到?