Yoldrim Yoldrim - 1 month ago 5
C++ Question

Replacing an char array with another

First time actually posting on here, quite excited hehe..

So we got this task from school to make a hangman game. I've done most of the difficult things, but there is one thing I can't seem to solve and google couldn't find the answer for me either, so here I am.

`int guess()
{
char letter[0];
int tries=0;
for(int i=0;i<length;i++)
{
meme[i]='_';
}
cout<<meme;
cout<<"Guess a letter: ";
cin>>letter;
while(strlen(letter) >= 2)
{
cout<<"Guess a letter: ";
cin>>letter;
}
for(int i=0;i<length;i++)
{
if(letter[0]==word[i])
{
meme[i]=letter[0];
}
else
{
//Fel bokstav
}
cout<<meme;
}
}`


"Meme" is the blank spaces, and what happens is that when I enter a correct letter, instead of replacing the '_'s in the char "Meme", I get something in the line of this (let's say the word is meme):

"Guess a letter: m"

"m___m___m_m_m_m_"

If anyone could help me out with this problem I'd be truly greatful. Thanks in advance!

Answer

The problem is that you do cout << meme inside your for loop. Because of that meme is printed once per character in your string (so four times). To fix it, just move cout << meme one line below, like this:

for(int i=0;i<length;i++)
{
    if(letter[0]==word[i])
    {
        meme[i]=letter[0];
    }
    else
    {
        //Fel bokstav
    }
}
cout<<meme;