我有以下代码,它应该作为命令获取用户输入,然后检查命令是否是预定义的.但是,对于输入的任何命令,输出是" 您要求帮助 ".我认为问题可能与我将用户输入字符串与设置字符串进行比较的方式有关,但我仍然需要帮助解决问题.
char command[10];
char set[10];
char set1[10];
strcpy(set, "help");
strcpy(set1, "thanks");
int a = 0;
while (a != 1)//the program should not terminate.
{
printf("Type command: ")
scanf("%s", command);
if (strcmp(set, command))
{
printf("You asked for help");
}
else if (strcmp(set1, command))
{
printf("You said thanks!");
}
else
{
printf("use either help or thanks command");
}
}
Run Code Online (Sandbox Code Playgroud)
if (strcmp(set, command))
Run Code Online (Sandbox Code Playgroud)
应该
if (strcmp(set, command) == 0)
Run Code Online (Sandbox Code Playgroud)
原因是strcmp如果LHS或RHS较大则返回非零值,如果它们相等则返回零.由于零在条件中评估为"假",因此您必须明确添加== 0测试,以使其在您期望的意义上成立,即相等.