从命令行获取参数时出现问题

Problem with getting arguments from command line

本文关键字:问题 参数 命令行 获取      更新时间:2023-10-16

strongtext我正试图从以下命令中获取参数:

./cube -d ../../data/input_small_id -q ../../data/query_small_id -k 5 -M 15 -p 6 -o out

我在获取k、M和p时遇到了一个问题。具体地说,我希望k、M、p是可选的_需求,而我的程序只得到我给它们的默认数字。所有的数字都是整数(k,M,probes(

void CubeUtils::getArgs(int argc,char **argv) {
int c ;
while (1) {
static struct option long_options[] =
{
//These options don’t set a flag.
//We distinguish them by their indices. 
{"d"         , required_argument , 0 , 'd'},
{"q"        , required_argument , 0 , 'q'},
{"k"    , optional_argument , 0 , 'k'},
{"M"           , optional_argument , 0 , 'M'},
{"probes"           , optional_argument , 0 , 'p'},
{"o"          , required_argument , 0 , 'o'},
{0, 0, 0, 0}
};
// getopt_long stores the option index here. 
int option_index = 0;
c = getopt_long (argc, argv, "d:q:k::M::p::o:a:h",
long_options, &option_index);
// Detect the end of the options. 
if (c == -1)
break;
switch (c) {
case 'd':
params.input_file.insert(0,optarg);
break;
case 'q':
params.query_file.insert(0,optarg);
break;
case 'k':
if (optarg) {
params.K = atoi(optarg);
}
else
params.K = 3 ;
break;
case 'M':
if (optarg) {
params.M = atoi(optarg);
}
else
params.M = 10 ;
break;
case 'p':
if (optarg) {
params.probes = atoi(optarg);
}
else
params.probes = 2 ;
break;
case 'o':
params.output_file.insert(0,optarg);
break;
case '?':
// getopt_long already printed an error message. 
break;
default:
abort ();
}
}
}

Params是包含参数的结构:

struct ParametersCube
{
string input_file;
string query_file;
int K;
int M;
int probes ;
string output_file;
float radius;
};

当它被执行时,我只接受默认的数字,而从不接受我通过命令行给出的数字。

这似乎是带有可选参数的预期行为。

引用optarg手册页:

optstring是一个包含合法选项字符的字符串。如果这样的字符后面跟着冒号,则该选项需要一个参数,因此getopt((将指向同一argv元素中的以下文本的指针,或指向optarg中的以下argv元素的文本的指针两个冒号表示一个选项采用可选arg;如果当前argv元素中有文本(即与选项名称本身相同的单词,例如"-oarg"(,则在optarg中返回文本,否则optarg设置为零

…和getopt手册页:

一个简单的短选项是一个"-"后面跟着一个短选项字符。如果选项有一个必需的参数,它可以直接写在选项字符后面,也可以作为下一个参数(即在命令行中用空格分隔(如果选项具有可选参数,则必须将其直接写入选项字符(如果存在(之后

就我个人而言,我觉得这很奇怪,但我可以确认,如果你把这些论点改为:

-k5 -M15 -p6

那么它就起作用了。

另请参阅:

带有可选参数的
  • getopt_long((选项