gpt4 book ai didi

c - 让 gcc getopt 示例接受长参数?

转载 作者:太空宇宙 更新时间:2023-11-04 02:50:14 25 4
gpt4 key购买 nike

我正在尝试获取以下 code使用命令

rectangle –area –length 12 –breadth 34

但是我得到了错误

rectangle: invalid option -- r

使用短参数选项

rectangle -a -l 12 -b 34

我得到了正确的答案

Area: 408

代码:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

/** Program to calculate the area and perimeter of
* a rectangle using command line arguments
*/
void print_usage() {
printf("Usage: rectangle [ap] -l num -b num\n");
}

int main(int argc, char *argv[]) {
int opt= 0;
int area = -1, perimeter = -1, breadth = -1, length =-1;

//Specifying the expected options
//The two options l and b expect numbers as argument
static struct option long_options[] = {
{"area", no_argument, 0, 'a' },
{"perimeter", no_argument, 0, 'p' },
{"length", required_argument, 0, 'l' },
{"breadth", required_argument, 0, 'b' },
{0, 0, 0, 0 }
};

int long_index =0;
while ((opt = getopt_long(argc, argv,"apl:b:",
long_options, &long_index )) != -1) {
switch (opt) {
case 'a' : area = 0;
break;
case 'p' : perimeter = 0;
break;
case 'l' : length = atoi(optarg);
break;
case 'b' : breadth = atoi(optarg);
break;
default: print_usage();
exit(EXIT_FAILURE);
}
}
if (length == -1 || breadth ==-1) {
print_usage();
exit(EXIT_FAILURE);
}

// Calculate the area
if (area == 0) {
area = length * breadth;
printf("Area: %d\n",area);
}

// Calculate the perimeter
if (perimeter == 0) {
perimeter = 2 * (length + breadth);
printf("Perimeter: %d\n",perimeter);
}
return 0;
}

最佳答案

长选项必须以 -- 为前缀,而不是单个 -

所以

rectangle –-area –-length 12 –-breadth 34

应该可以。

更新

也可以使用以下形式:

rectangle –-area –-length=12 –-breadth=34

您可能希望通过更改来更正用法声明:

printf("Usage: rectangle [ap] -l num -b num\n");

printf("Usage: rectangle [-a|--area -p|--perimeter] -l|--length num -b|--breadth num\n");

关于c - 让 gcc getopt 示例接受长参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22910112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com