I am just learning C and I made a very simple, hacky hangman game. What I can't figure out is why the expected output gets doubled everytime I make a guess.
#include <stdio.h>
#include <string.h>
int main()
{
setbuf(stdout, NULL);
char word[] = "pretzels";
char guessed[50];
memset(guessed, '0', sizeof(guessed));
int len;
char guess;
char buf;
len = strlen(word);
int j;
printf("Welcome to Hangman!\n");
for (int i=0; i<len; i++) {
if (guessed[i] != '0') {
printf("%c ", word[i]);
}
else {
printf("_ ");
}
}
while(memcmp(word, guessed, len) != 0) {
printf("\nGuess a letter: ");
scanf("%c", &guess);
for (j=0; j<len; j++) {
if (word[j] == guess && word[j] != guessed [j]) {
guessed[j] = guess;
break;
}
}
for (int i=0; i<len; i++) {
if (guessed[i] != '0') {
printf("%c ", word[i]);
}
else {
printf("_ ");
}
}
}
printf("\nYou got it!");
return 0;
}
The output of this program then looks like this...
Welcome to Hangman!
_ _ _ _ _ _ _ _
Guess a letter: p
p _ _ _ _ _ _ _
Guess a letter: p _ _ _ _ _ _ _
Guess a letter: r
p r _ _ _ _ _ _
Guess a letter: p r _ _ _ _ _ _
Guess a letter: e
p r e _ _ _ _ _
Guess a letter: p r e _ _ _ _ _
etc... Every time the output starts again it prints the line right before scanf, skips the scanf and then goes on to do the for loop that draws the word/spaces again.
Why is my output doubling?? I must be missing something.