Search code examples
cif-statementlogical-operatorsc-stringsstrcmp

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


I am trying to check if the user string input (after lowercasing user input) matches with required three strings i.e. rock or paper or scissor. If it doesn't match the requirement the system will print It is a wrong input. Otherwise, I'll do something.

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.

Being a beginner I couldn't figure out the possible reason after searching in StackOverflow also. Any help in advance. Thank you 🙏

#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 */
    }
    
}

Solution

  • You've got your conditions mixed up.

    If you want to 'do something', if it's any of these strings, you need to check for 'equal', as in:

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

    Alternatively you can do a cascade:

    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");
    

    This has the same effect with the bonus effect of telling you exactly, which the user has input.

    If you wanted to check whether it is NONE of the options, you'll need to use &&.