【问题标题】:getopt: not recognizing valid command line argumentsgetopt:无法识别有效的命令行参数
【发布时间】:2014-01-26 08:41:37
【问题描述】:

我在 linux 环境中进行 C++ 编程,我正在尝试使用 getopt 解析命令行参数。我想要一个输入 -s 或 -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;

}

这在顶部包含正确的#include,并且编译得很好。

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

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

【问题讨论】:

    标签: c++ getopt getopt-long


    【解决方案1】:

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

    这会导致从o 下降到:?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-01
      • 2016-06-10
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 2020-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多