基本C刽子手代码问题

时间:2015-01-22 11:46:46

标签: c

嘿伙计们我正在学习C,我开始编写一个Hangman游戏。这应该超过1个单词,我选择" informatik"。

我想要做的是询问用户名,然后开始。

#include<stdio.h>            
 int main() {
int correct = 0;
int mistake = 0;
int number = 0;
char name[20];
char Word[]={'i','n','f','o','r','m','a','t','i','k'};
char guessStatus[]={'_','_','_','_','_','_','_','_','_','_','\0'};
char guess;
printf("##### Welcome to Hangman #####\nWhat is your Name?\n");
scanf(" %s", name);
fflush(stdin);
printf("Hello %s!\n", name);                                                                               
   while (mistake <=10 && number<10) {
    printf("Guess a letter: ");
    guess = getchar();
    printf("%c", guess);
    correct = 0;
    for (int search=0; search<10; search++)
    {                                                


        if (guess == Word[search]){
            number++;
            guessStatus[search] = Word[search];
            correct = 1;
        }
    }
    if (correct == 0){
        mistake++;
        printf("%c is wrong!\nYour Status is: %s\nYou have %i tries left\n", guess,guessStatus,10-mistake);
    }
        else {
            printf("Good job %s!\nYour Status is: %s\nYou have %i tries left\n", name,guessStatus,10-mistake);
        }

}

}

问题是当我运行代码并输入任何字母时,程序计数&#34;输入&#34;也作为一封信。我使用fflush(stdin)作为希望,即使我对此一无所知,但没有工作:) 问题输出如:

欢迎来到Hangman

你的名字是什么? 约翰 你好约翰! 猜一封信:

错了! 您的状态是:__________ 你还有9次尝试 猜一封信:我 iGood工作约翰! 您的状态是:i_______ i_ 你还有9次尝试 猜一封信:

错了! 您的状态是:i_______ i_ 你有8次尝试

我不知道如何处理它。帮助将非常感激。

2 个答案:

答案 0 :(得分:0)

试试这个应该工作 使用

scanf(" %c",&guess);

而不是

guess = getchar();   //remove this line
printf("%c",  guess); //remove this line also

答案 1 :(得分:0)

添加gethcar();可以阅读\ n:

#include <stdio.h>            
 int main() {
int correct = 0;
int mistake = 0;
int number = 0;
char name[20];
char Word[]={'i','n','f','o','r','m','a','t','i','k'};
char guessStatus[]={'_','_','_','_','_','_','_','_','_','_','\0'};
char guess;
printf("##### Welcome to Hangman #####\nWhat is your Name?\n");
scanf(" %s", name);
getchar(); // add this line
printf("Hello %s!\n", name);                                                                               
   while (mistake <=10 && number<10) {
    printf("Guess a letter: ");
    guess = getchar();
    printf("%c", guess);
    correct = 0;
    for (int search=0; search<10; search++)
    {                                                


        if (guess == Word[search]){
            number++;
            guessStatus[search] = Word[search];
            correct = 1;
        }
    }
    if (correct == 0){
        mistake++;
        printf("%c is wrong!\nYour Status is: %s\nYou have %i tries left\n", guess,guessStatus,10-mistake);
    }
        else {
            printf("Good job %s!\nYour Status is: %s\nYou have %i tries left\n", name,guessStatus,10-mistake);
        }
}
}