Xarigizel
Xarigizel

Reputation: 59

Trouble with strchr in C

I can't work out why Strchr() is not working in my function. I need to see if the users guess matches any of the letters in a hidden word. It is a Hangman game.

int guessLetter(char* word, int* guessedLetters)
{
    char guess[20];
    char *s;

    printf("Enter your guess: ");
    scanf("%s", &guess);

    s = strchr (word, guess);
    printf("%s", s);

    if (s != NULL) {
        printf ("Good Guess\n");
    } else {
        printf ("Bad Guess\n");
    }

}

No matter if the guess is right or wrong, my else statement is being activated. My printf shows that s is being given the value of Null no matter if the character is in the word or not.

So I guess my problem is with this part of the code:

s = strchr (word, guess);

I am new to C, so I am sure I am just missing something very basic. I have tried to search the web as much as I can, but I don't really seem to be able to understand what I am doing wrong.

Upvotes: 0

Views: 1760

Answers (1)

P.P
P.P

Reputation: 121387

strchr takes an int as 2nd argument but you are passing a char*. You Turn on your compiler warnings.

What you wanted is to loop over the word to see if any of the characters are in guess.

s = 0;
for(size_t i=0; word[i]; i++) {
    s = strchr (guess, word[i]);
    if(s) break; //Found a match
}

This would break on the first match and you can modify it if you want to check for all characters in word.

There's an argument mismatch in scanf call too:

scanf("%s", &guess);

should be

scanf("%s", guess);

scanf expects a char* for format string %s but you are passing char(*)[20] i.e. &guess is of type char (*)[20].

Upvotes: 2

Related Questions