gpt4 book ai didi

c - 如何将整数作为命令行参数?

转载 作者:太空狗 更新时间:2023-10-29 16:28:12 26 4
gpt4 key购买 nike

我读过 a getopt() example但它没有显示如何接受整数作为参数选项,例如 cvalue 将出现在示例代码中:

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

int
main (int argc, char **argv)
{
int aflag = 0;
int bflag = 0;
char *cvalue = NULL;
int index;
int c;

opterr = 0;

while ((c = getopt (argc, argv, "abc:")) != -1)
switch (c)
{
case 'a':
aflag = 1;
break;
case 'b':
bflag = 1;
break;
case 'c':
cvalue = optarg;
break;
case '?':
if (optopt == 'c')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}

printf ("aflag = %d, bflag = %d, cvalue = %s\n",
aflag, bflag, cvalue);

for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}

如果我以 testop -c foo 运行上面的代码,cvalue 将是 foo,但是如果我想要 testop - c 42?由于 cvaluechar * 类型,我可以将 optarg 转换为 (int) 吗?我试过在不使用 getopt() 并直接访问 argv[whatever] 并将其转换为整数的情况下执行此操作,但我总是以一个大的负数结束使用 %d 打印时。我假设我没有正确取消引用 argv[] 之类的,不确定...

最佳答案

您需要使用atoi() 将字符串转换为整数。

关于c - 如何将整数作为命令行参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4796662/

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