使用 || 比较多个字符串C语言中逻辑运算符不能正常工作

Comparing Multiple Strings Using || Logical Operator Is Not Working Properly in C language

我正在尝试检查用户字符串输入(在小写用户输入后)是否与所需的三个字符串匹配rock or paper or scissor.如果不符合要求,系统会打印It is a wrong input。不然,我就做点什么。

When I'm giving only one check without the logical || operator, it is working fine i.e. comparing the user input string with the required one. But when I'm using logical operator it is not working properly i.e. if I give right keyword, it is saying that it is a wrong input.

作为初学者,我在 Whosebug 中搜索后也无法找出可能的原因。提前提供任何帮助。谢谢

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main()
{
    char game[40];
    printf("Enter one among rock, paper and scissor: ");
    scanf("%s", &game);
    for (int i = 0; game[i]; i++)
    {
        game[i] = tolower(game[i]);
    }
    if ((strcmp("rock", game) != 0) || (strcmp("paper", game) != 0) || (strcmp("scissor", game) != 0))
    {
        printf("You entered a wrong input\n");
    }
    else
    {
        /* Do Something */
    }
    
}

你的条件搞混了。

如果你想 'do something',如果是这些字符串中的任何一个,你需要检查 'equal',如:

if (!strcmp("rock", game) || !strcmp("paper", game) || !strcmp("scissor", game))
{
   //Do something
}
else
{
    printf("You entered a wrong input\n");
}

或者您可以进行级联:

if (!strcmp("rock", game))
    //Do something for rock
else if (!strcmp("paper", game))
    //Do something for paper
else if (!strcmp("scissors", game))
    //Do something for scissors
else
    printf("Wrong input\n");

这与用户输入的准确告诉你的奖励效果相同。

如果你想检查它是否是NONE个选项,你需要使用&&