我需要将负数传递给getopt,并且我想知道是否有一种简单的方法可以将getopt使用的前缀(即' - '字符在case语句中标记)更改为不同的字符像' - '或'+'。将负数传递给Getopt
我是否需要使用Getopt :: Long来更改前缀?
我需要将负数传递给getopt,并且我想知道是否有一种简单的方法可以将getopt使用的前缀(即' - '字符在case语句中标记)更改为不同的字符像' - '或'+'。将负数传递给Getopt
我是否需要使用Getopt :: Long来更改前缀?
我不认为有一种方法可以将命令行参数前缀更改为除-
(或--
使用getopt_long()
)之外的任何内容。但是,如果您需要传递负数,则应该将参数定义为“required_argument”。例如,下面是一个使用getopt_long_only
方法获取命令行参数的简短getopt的方法:
// personaldetails.cpp
// compile with:
// g++ -std=c++11 personaldetails.cpp -o personaldetails
#include <iostream>
#include <string>
#include <vector>
#include <getopt.h>
int main (int argc, char** argv)
{
// Define some variables
std::string name = "" ;
int age = 0 ;
double weight = 0.0 ;
// Setup the GetOpt long options.
std::vector<struct option> longopts ;
longopts.push_back({"Name", required_argument, 0, 'N'}) ;
longopts.push_back({"Age", required_argument, 0, 'A'}) ; // <- IMPORTANT
longopts.push_back({"Weight",required_argument, 0, 'W'}) ; // <- IMPORTANT
longopts.push_back({0,0,0,0}) ;
// Now parse the options
while (1)
{
int c(0) ;
int option_index = -1;
c = getopt_long_only (argc, argv, "A:N:W:",
&longopts[0], &option_index);
/* Detect the end of the options. */
if (c == -1) break;
// Now loop through all of the options to fill them based on their values
switch (c)
{
case 0:
/* If this option set a flag, do nothing else now. */
break ;
case '?':
// getopt_long_omly already printed an error message.
// This will most typically happen when then an unrecognized
// option has been passed.
return 0 ;
case 'N':
name = std::string(optarg) ;
break ;
case 'A':
age = std::stoi(optarg) ;
break ;
case 'W':
weight = std::stod(optarg) ;
break ;
default:
// Here's where we handle the long form arguments
std::string opt_name(longopts[option_index].name) ;
if (opt_name.compare("Name")==0) {
name = std::string(optarg) ;
} else if (opt_name.compare("Age")==0) {
age = std::stoi(optarg) ;
} else if (opt_name.compare("Weight")==0) {
weight = std::stod(optarg) ;
}
break ;
}
}
// Print the persons details
std::cout << "Name : " << name << std::endl;
std::cout << "Age : " << age << std::endl;
std::cout << "Weight: " << weight << std::endl;
return 0 ;
}
这里的关键部分是,在longopts
我设置我要转换成整数的参数和双倍有required_argument
。这告诉GetOpt到期望另一个参数,你已经在命令行上声明它。这意味着GetOpt将在参数的命令行参数之后的参数中读入该命令行参数。对于我们想要通过单个参数(即-N
,-A
或-W
)的情况,这里通过"N:A:W:"
来getopt很重要。 :
对于单个字符参数基本上做同样的事情,如required_argument
对长格式所做的那样。
运行脚本我可以这样做:
$ ./personaldetails -Name Sally -Age -45 -Weight 34.5
Name : Sally
Age : -45
Weight: 34.5
$./personaldetails -N Sally -A -45 -W -34.5
Name : Sally
Age : -45
Weight: -34.5
注意,因为脚本使用getopt_long_only()
我可以传递参数参数的长形式单一-
。