我是C编程的初学者。我有两个问题!
1.当我使用命令guess = getchar();
获取char的输入时,它首次接受输入,但在下一次循环运行时跳过!这就是我使用数组存储用户输入的字符的原因!
我的代码运行正常,但我不知道如何在这个游戏中打印刽子手。任何的想法?
问候!
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define interface for (int a = 0; a < 50 ; a++) printf("*");
#define space for (int a = 0; a < 15 ; a++) printf (" ");
void MENU()
{
interface;
printf("\n");
space;
printf("Welcome to HANGMAN GAME!\n");
interface;
printf("\n");
space;
printf("Rules\n- Guess a single letter!\n- Number of lives are 5 in number!\n");
printf("- Wrong guess will cause you to loose one life!\n- Repetition of a letter will cause you to loose a life!\n");
printf("- To quit in middle of the game. Type in quit!\n");
}
int main(){
int wordlength, index, oldcorrect;
char guess;
srand(time(NULL));
char guesschecker[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
char guessword[][10] = {
"windows",
"cupboard",
"sharpener",
"lifeguard" };
char letterguessed[10];
int correctguess = 0;
int lives = 5;
int loopindex;
int quit = 0;
MENU();
index = rand() % 4;
wordlength = strlen(guessword[index]);
/*
printf("\nindex: %d word : %s wrodlength : %d\n", index, guessword[index], wordlength);
*/
while (correctguess < wordlength){
printf("\nHangman word: ");
for (loopindex = 0; loopindex < wordlength; loopindex++)
{
if (guesschecker[loopindex] == 1){
printf("%c ", guessword[index][loopindex]);
}
else printf("_ ");
}
printf("\n\nLetter correct so far : %d", correctguess);
printf("\nEnter your guess letter : ");
fgets(letterguessed, 10, stdin);
if (strncmp(letterguessed, "quit", 4) == 0){
quit = 1;
break;
}
guess = letterguessed[0];
printf("Your guess is : %c\n", guess);
oldcorrect = correctguess;
for (loopindex = 0; loopindex < wordlength; loopindex++)
{
if (guesschecker[loopindex] == 1){
continue;
}
if (guess == guessword[index][loopindex])
{
guesschecker[loopindex] = 1;
correctguess++;
}
}
if (oldcorrect == correctguess)
{
lives--;
printf("Wrong guess!\n");
if (lives == 0)
break;
}
else printf("Correct guess!\n");
printf("Your lives left are : %d", lives);
}
if (quit == 1)
printf("You quit early!");
else if (lives == 0){
printf("Sorry You are out of lives!\n");
printf("The correct word was : %s", guessword[index]);
}
else printf("You Won! Yayy!");
_getch();
return 0;
}
答案 0 :(得分:1)
getchar();
之后添加guess=getchar();
即可解决问题。printf
和if
s