Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my C code say char matches other char even tho it does?

I am making a simple hangman game in C, I am trying to check if each character in the string matches the guessed character. but when I test it, it gives results that are incorrect and shouldn’t have passed the if statement in the first place. for example when I enter the letter a (The word is apple) it give me a__a. somehow the word became 4 letters long instead of 5 and it said that the last letter is a even tho it isn’t.

https://imgur.com/a/DZDTbbj

#include <stdio.h>

int main() {
    int size = 0;
    char word[] = "apple", guess, hidden[size];
    while (word[size] != '\0') {
        size++;
    }
    for (int i = 0; i < size; ++i) {
        hidden[i] = '_';
    }

    while (1) {
        printf("%s\n", hidden);
        scanf(" %c", &guess);
        for (int y = 0; y < size; ++y) {
            if (word[y] == guess) {
                hidden[y] = guess;
            }
        }
    }
    return 0;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You declare hidden[size] before the loop that sets size to the length of word. So it’s using the initial value 0 as the length of the array.

Move that declaration down to after the loop. Also, you need to make the length size+1 to allow room for the null terminator, and then add the null terminator.

int main()
{
    int size=0;
    char word[]="apple",guess;
    while(word[size]!='\0'){
        size++;
    }
    char hidden[size+1];
    for (int i = 0; i < size; ++i)
    {
        hidden[i]='_';
    }
    hidden[size] = '\0';

    while(1){
        printf("%s\n",hidden );
        scanf(" %c",&guess);
        for (int y = 0; y < size; ++y)
        {
            if (word[y] == guess)
            {
                hidden[y]=guess;
            }
        }
    }

    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading