Cannot convert source type 'int' to target type 'string'

I am creating a hangman game right now. The error in the title pops up while my code tries to translate user inputs into string . Could anyone kindly give me some hints?

static void Main(string[] args)
        {
                int amountOfLettersRevealed = 0;
                Console.WriteLine("Welcome to Hangman!!!!!!!!!!");
                Console.InputEncoding = Encoding.Default;
                string[] listwords = File.ReadAllLines(@"/Users/annamusterfrau/Desktop/C#_co/italian.txt");
                Random randGen = new Random();
                var idx = randGen.Next(0, 9);
                string mysteryWord = listwords[idx];
                string[] hangman = new string[mysteryWord.Length];
                Console.Write("Please enter your guess: ");

                for (int p = 0; p < mysteryWord.Length; p++)
                {
                    hangman[p] = "*";
                }
                
                while (true)
                {
                    string playerGuess;
                    playerGuess = Console.ReadLine();
                    var guessed = Int32.Parse(playerGuess);
                    //char playerGuess = char.Parse(Console.ReadLine());
                    for (int j = 0; j < mysteryWord.Length; j++)
                    {
                        if (guessed == mysteryWord[j])
                        {
                          //Cannot convert source type 'int' to target type 'string'
                           hangman[j] = guessed;
                           amountOfLettersRevealed++;

                        }
                        
                        
                    }
                    Console.WriteLine(hangman);

                    
                    
                    if (hangman.Length == amountOfLettersRevealed)
                    {
                        Console.WriteLine("hip hip hurray");
                    }

                    
                    
                }
        }

Hi,
The line;

var guessed = Int32.Parse(playerGuess);

is setting ‘guessed’ as being an int. I assume you want it to be a character.
So,

hangman[j] = guessed;

is trying to set a string to be an int - the error.
The way I’d do it is probably;

char guessed = playerGuess[0];

As playerGuess is a string, then [0] will just be the first char of that string.

Hope that helps

Thank you so much! This helped me a lot :slight_smile:

1 Like