0

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.

Adam D
  • 1,962
  • 2
  • 21
  • 37
  • Think about what you type and what scanf reads. – prl Sep 17 '17 at 03:46
  • 2
    Scanf is a poor choice for interactive input. There are plenty of answers here about what to use instead. – prl Sep 17 '17 at 03:48
  • @ArtemBarger it's good to have extra features in the language. – CroCo Sep 17 '17 at 03:53
  • @CroCo but why not just use `while(memcmp(word, guessed, len) != 0)` ? Its shorter and more easy to follow – Mitch Sep 17 '17 at 03:57
  • @Mitchel0022 blame the programmer not the language. :) – CroCo Sep 17 '17 at 03:58
  • @CroCo Thanks for that suggestion. I've updated the code with that, but still the same problem with output. That's really what the question was about. – Adam D Sep 17 '17 at 04:14

1 Answers1

0

you can use _flushall() right after the scanf, the buffer expect to get a char character and when you enter a char you enter the char and also enter.

piscoony
  • 31
  • 5