-4

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(game, "rock") == 1) || (strcmp(game, "paper") == 1) || (strcmp(game, "scissor") == 1))
    {
        printf("You entered a wrong input\n");
    }
    else
    {
        /* Doing Something */
    }
    
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

3 Answers3

2

Read The Friendly Manual: man strcmp

The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

That is, in case the strings match, strcmp returns 0.

So to check if something is not a match, De Friendly Morgan says that we should do:
a!=0 AND b!=0 AND ....

Lundin
  • 195,001
  • 40
  • 254
  • 396
1

From the description of the function strcmp in the C Standard *7.23.4.2 The strcmp function)

3 The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

That is the function can return any integer number greater or less than zero in case when strings are not equal each other. If two strings are equal each other then the function returns 0.

So rewrite the if statement

if ((strcmp(game, "rock") == 1) || (strcmp(game, "paper") == 1) || (strcmp(game, "scissor") == 1))
{
    printf("You entered a wrong input\n");
}

the following way

if ( strcmp(game, "rock") != 0 && strcmp(game, "paper") != 0 && strcmp(game, "scissor") != 0 )
{
    printf("You entered a wrong input\n");
}

That is when the entered string is not equal to all of the required strings.

Pay attention to that instead of

scanf("%s", &game);
           ^^^

you have to write

scanf("%s", game);
           ^^^
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Just change

if ((strcmp(game, "rock") == 1) || (strcmp(game, "paper") == 1) || (strcmp(game, "scissor") == 1))

to

if ((strcmp(game, "rock") != 0) && (strcmp(game, "paper") !== 0) && (strcmp(game, "scissor") != 0))
Saurabh Dhage
  • 1,478
  • 5
  • 17
  • 31