作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我读过 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
?由于 cvalue
是 char *
类型,我可以将 optarg
转换为 (int)
吗?我试过在不使用 getopt()
并直接访问 argv[whatever]
并将其转换为整数的情况下执行此操作,但我总是以一个大的负数结束使用 %d
打印时。我假设我没有正确取消引用 argv[]
之类的,不确定...
最佳答案
您需要使用atoi()
将字符串转换为整数。
关于c - 如何将整数作为命令行参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4796662/
我是一名优秀的程序员,十分优秀!