1

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--;
                }
            }
        }
    }
2
  • 1
    You can use Console.ReadKey().KeyChar instead of Console.ReadLine() since you want only a single character from the user. Commented Mar 14, 2018 at 22:28
  • if(userInputGuess[0] == letter) Commented Mar 14, 2018 at 22:31

2 Answers 2

6

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Two things here: userInputGuess[0] would throw an IndexOutOfRangeException if the user just pressed enter (generating an empty string); and userInputGuess would have to be declared as char for the second approach to work
Agreed. I missed that for the char declaration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.