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

Time:12-30

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;
}

CodePudding user response:

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;
}
  • Related