hoe getopt()处理字符类型
我有一个关于getopt函数的问题,如下代码所示,“ch”的类型是“int”,但在switch子句中,它被视为“char”。。我很困惑为什么 坦斯克hoe getopt()处理字符类型,getopt,Getopt,我有一个关于getopt函数的问题,如下代码所示,“ch”的类型是“int”,但在switch子句中,它被视为“char”。。我很困惑为什么 坦斯克 int main(int argc, char **argv) { extern int optind; extern char * optarg; int ch; char * format = "f:hnBm:"; // Default makefile name will be Makefile char szMakefile[64]
int main(int argc, char **argv)
{
extern int optind;
extern char * optarg;
int ch;
char * format = "f:hnBm:";
// Default makefile name will be Makefile
char szMakefile[64] = "Makefile";
char szTarget[64];
char szLog[64];
while((ch = getopt(argc, argv, format)) != -1)
{
switch(ch)
{
case 'f':
strcpy(szMakefile, strdup(optarg));
break;
case 'n':
break;
case 'B':
break;
case 'm':
strcpy(szLog, strdup(optarg));
break;
case 'h':
default:
show_error_message(argv[0]);
exit(1);
}
}
在C语言中,
char
实际上只是一个特定大小的整数,int
可以隐式转换成一个整数,因此它的工作方式是透明的。当您在C语言中比较char和int时(例如在您的switch语句中),编译器会自动将char转换为int类型。因此,在上面的switch语句中,“f”自动转换为102,这是对应于ASCII“f”的数值。因此,在代码中的switch语句中,“ch”并不是真正的字符。相反,case语句中的字符都被强制转换为int,因此它们匹配“ch”的类型,但当我打印f(“%d”,ch)时,无论我键入“f”、“B”或“m”,它都会给我一个值1……似乎没有区别。但是当我打印f(“%d”,ch)时,无论我键入“f”、“B”或“m”,它都会给我一个值1……似乎没有区别。你知道为什么我在循环开始时添加了printf
,并看到了不同的数字,然后运行了你问题中的确切代码吗。粘贴代码时是否更改了代码中的某些内容。。。?