我只是学习C而且我做了一个非常简单,hacky的刽子手游戏。我无法弄清楚的是为什么每当我猜测时预期的输出都会加倍。
#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;
}
这个程序的输出看起来像这样......
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 _ _ _ _ _
等...每次输出再次开始时,它会在scanf之前打印一行,跳过scanf ,然后继续执行再次绘制单词/空格的for循环。
为什么我的输出加倍?我一定错过了什么。
答案 0 :(得分:0)
你可以在scanf之后立即使用_flushall(),缓冲区期望获得一个char字符,当你输入一个char时输入char并输入。