问题描述
我想一个OPTARG值赋给一个int,但是编译器给了我以下警告:
警告:赋值时将指针整数,未作施放[默认启用]
我试图铸造OPTARG为int的赋值之前
N =(INT)OPTARG;
但仍得到一个警告:
警告:从指针转换为大小不同的整数[-Wpointer对INT-投]
我不知道需要之前,我可以简单地OPTARG分配到一个整数,然后打印(现在)做什么。
INT主(INT ARGC,CHAR *的argv [])
{
焦炭℃;
INT N; 而((c = getopt的(ARGC,ARGV,M))!= -1){
开关(三){
案件的m:
N = OPTARG;
打破;
}
} 的printf(%d个\\ N,N); 返回0;
}
选项字符串的总是的字符串。
如果你想要一个整数,你需要使用一个转换功能,像的
所以,你应该至少code
N =的atoi(OPTARG);
当心, OPTARG
可能是 NULL
,当然可能是一个非数字。您可以使用可以设置结束字符你会检查。
因此,一个更严重的办法是
情况下,M:
{
字符* ENDP = NULL;
长L = -1;
如果(OPTARG ||((L =与strtol(OPTARG,0,&安培;!ENDP)),(ENDP和放大器;&放大器; * ENDP)))
{fprintf中(标准错误,无效-m选项%S - 期待一个数字\\ n
OPTARG OPTARG:);
出口(EXIT_FAILURE);
};
//你可以开左增加更多的检查,这里...
N =(INT)升;
打破;
}
N = OPTARG;
打破;
顺便说一句,GNU库也有功能(和还 - 但 argp
功能更强大的),您可能会发现更方便。几个框架(尤其是基于GTK和Qt)也有程序参数传递的功能。
如果你正在做一个严肃的节目,请让它接受 - 帮助
选项,如果可能的话 - 版本
之一。这真的很方便,我恨它不接受他们的一些程序。看看说。
I am trying to assign an optarg value to an int, but the compiler gives me the following warning:
warning: assignment makes integer from pointer without a cast [enabled by default]
I have tried casting optarg as int before the assignment
n = (int) optarg;
but still get a warning:
warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
I am not sure what needs to be done before I can simply assign the optarg to an integer, then print it (for now).
int main (int argc, char *argv[])
{
char c;
int n;
while ((c = getopt(argc, argv, "m:")) != -1) {
switch (c) {
case 'm':
n = optarg;
break;
}
}
printf("%d\n", n);
return 0;
}
The option string is always a string.
If you want an integer, you need to use a conversion function, like atoi(3)
So you should at least code
n = atoi(optarg);
Beware, optarg
could be NULL
and could certainly be a non-number. You might use strtol(3) which may set the ending character which you would check.
So a more serious approach could be
case 'm':
{
char* endp = NULL;
long l = -1;
if (!optarg || ((l=strtol(optarg, 0, &endp)),(endp && *endp)))
{ fprintf(stderr, "invalid m option %s - expecting a number\n",
optarg?optarg:"");
exit(EXIT_FAILURE);
};
// you could add more checks on l here...
n = (int) l;
break;
}
n = optarg;
break;
BTW, GNU Libc also have argp functions (and also getopt_long - but argp
functions are more powerful), which you may find more convenient. Several frameworks (notably Gtk and Qt) have also program argument passing functionalities.
If you are doing a serious program please make it accept the --help
option, and if possible the --version
one. It is really convenient, and I hate the few programs which don't accept them. See what GNU standards say.
这篇关于分配OPTARG在C的int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!