estevaano
estevaano

Reputation: 13

Comparing a string and a char c#

I am working on a console Hangman game in c#. I am trying to compare user inputted letter against the letters in the random word I have generated. Error i get is "Operator "==" cannot be applied to operands of type "string" and "char". What other ways could I go about doing this? Ive googled a lot but I haven't found any ideas.

public static void LetterChecker(string word)
    {
        int userGuesses = 6;
        string userInputGuess;

        while(userGuesses > 0)
        {
            Console.WriteLine("Please guess a letter");
            userInputGuess = Console.ReadLine();
            foreach(var letter in word)
            {
                if(userInputGuess == letter)
                {
                    Console.WriteLine("this letter is in word, guess again");
                }
                else
                {
                    Console.WriteLine("Incorrect guess");
                    userGuesses--;
                }
            }
        }
    }

Upvotes: 1

Views: 2151

Answers (2)

m3n7alsnak3
m3n7alsnak3

Reputation: 3166

The return type of Console.ReadLine() is a string. By this your userInputGuess is of type string, and this is why you receive the error. With slight modification your code can work. Instead of:

if(userInputGuess == letter)

use:

if(userInputGuess[0] == letter)

This will read the first letter of your line. But as you may guess, this is not the best solution in this case.

The better approach would be to read only one letter from the console. Like this:

var userInputGuess = Console.ReadKey().KeyChar; (and get rid of the previous declaration)

The result of this is of type char, and you won't have a problem in the comparison.

Upvotes: 0

Camilo Terevinto
Camilo Terevinto

Reputation: 32072

Instead of using Console.ReadLine which reads an entire line, use Console.ReadKey:

Obtains the next character or function key pressed by the user.
The pressed key is displayed in the console window.

char userInputGuess;
...
Console.WriteLine("Please guess a letter");
userInputGuess = Console.ReadKey().KeyChar;

Upvotes: 6

Related Questions