【问题标题】:GetOpt Long recognizing VerboseGetOpt Long 识别 Verbose
【发布时间】:2013-11-03 17:22:15
【问题描述】:

现在,我正试图让我的程序正确地重新识别我在命令行中传递给它的标志。鉴于 MineEscape 是可执行文件的名称,以下命令行 ./MineEscape --container BINARY infile.txt 可以正常工作。但是,我在让这个命令行工作时遇到问题,./MineEscape --verbose 15 -c PAIRING infile.txt > outfile.txt

另请注意,命令行的必需标志是 --container 和一种容器类型,例如 PAIRING 或 BINARY。以及 --verbose 后面应该跟一个整数。

当运行不正确的命令行时,我遇到了详细部分的问题,说存在段错误。

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


struct arguments{
    bool binary;
    bool poorMan;
    bool sorted;
    bool pairing;
    int outputStatistics;
} choice;

const struct option longOpts[]{
    {"help",optional_argument,NULL,'h'},
    {"container",required_argument,NULL,'c'},
    {"verbose",optional_argument,NULL,'v'}
};

stringstream ss;

int opt=0,longIndex=0;
opt=getopt_long(argc,argv,"v:c:h",longOpts,&longIndex);
while(opt!=-1){
    switch(opt){
        case 'h':
            //Print out description of executable

            exit(0);
            break;
        case 'c':
            if(!strcmp("BINARY",optarg))
                choice.binary=1;
            else if(!strcmp("POOR_MAN",optarg))
                choice.poorMan=1;
            else if(!strcmp("SORTED",optarg))
                choice.sorted=1;
            else if(!strcmp("PAIRING",optarg))
                choice.pairing=1;
            else{
                ss<<"Sorry, not a valid container implementation\n";
                cout<<ss.str();
                exit(0);
            }
            break;
        case 'v':
            if(atoi(optarg)>0)
                choice.outputStatistics=atoi(optarg);
            else{
                ss<<"Sorry, requires a value greater than 0\n";
                cout<<ss.str();
                exit(0);
            }
            break;
        default:

            break;
    }
    opt=getopt_long(argc,argv,"v:c:h",longOpts,&longIndex);
}
}

【问题讨论】:

    标签: c++ getopt-long


    【解决方案1】:

    您会发现 'optarg' 的值为 NULL,尽管它被指定为 "v:"。

    我发现如果使用“-v3”或“-v 3”,例如,可以解析。但“--verbose 3”失败,“--verbose=3”有效。

    奇怪的是,这种行为似乎只适用于可选参数。

    这个link 有更多

    gcc 4.4.6

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多