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

getopt: not recognizing valid command line arguments

本文关键字:命令行 参数 有效 识别 getopt      更新时间:2023-10-16

我是Linux环境中的C 编程,我正在尝试使用GetOpt解析命令行参数。我想需要一个输入-s或-Q(分别分别 - stack和 - Quele),而不是兼具的输入-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;

}

这包含顶部的适当#CRUDES,并填充了罚款。

但是,当我尝试运行./-hunt -q -o m时,cases'q','o',':'和'和'?'全部执行。我决定输出任何角色触发":和"?块,控制台显示111个字符" O"的ASCII值。

这对我来说是极其混乱的,因为在GetOpt触发了" O"块之后,是否应该返回-1表示没有更多的命令行参数?感谢任何帮助/建议。谢谢!

您在case 'o'case ':'中缺少break

这会导致从o:?