我有困难比较两个字符。我写了一个非常基本的C问题来尝试使用命令行参数。
以下是我的代码:
我得到的输出如下:
以下是我的代码:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
char ch;
char *type = "";
char *gender = "";
int baby = 0;
int count = 0;
/* Options:
* -t = type of pet
* -g = gender
* -b = baby or adult
*/
while ((ch = getopt(argc, argv, "t:g:b")) != EOF)
switch (ch) {
case 't':
type = optarg;
break;
case 'g':
gender = optarg;
break;
case 'b':
baby = 1;
break;
default:
fprintf(stderr, "Invalid option.\n");
return 1;
}
argc -= optind;
argv += optind;
printf("You have chosen a %s.\n", type);
if (gender == 'f')
puts("It's a girl");
if (gender == 'b')
puts("It's a boy.");
// The main command line arguments should be about the traits of the pet
printf("%s", "Traits: ");
for (count = 0; count < argc; count++)
printf("%s ", argv[count]);
return 0;
}
所以如果我在终端中输入以下内容:
$ ./pet_shop -t dog -g f cute small
我得到的输出如下:
You have chosen a dog:
Traits: cute small
输出的信息缺少有关性别的信息,因为我输入了f,所以应该是一个女孩。但是我通过printf("%i", gender)尝试检查,结果却是0。g == 'f'是比较两个字符的错误方式吗?
char *type = "";
的定义是只读的,也就是说,一旦声明了type
,你就不能直接将字符串赋值给它。请阅读此文档 - http://msdn.microsoft.com/en-us/library/8kc54dd5(v=vs.80).aspx - Nobilischar*
变量则不是。 - Fred Fooch
声明为int
,否则在某些平台上可能无法正确处理EOF
。 - JeremyP