我为我的常见Hangman问题烦扰这个论坛而道歉。我希望很快就能做到这一点。真的在努力工作。到目前为止,这是我的代码:
#include <stdio.h>
#include <time.h>
#include <string.h>
#define MAX_WORD_LEN 20
#define MAX_TRIES 6
char* GetWordFromFile();
int HideWord(char* randomWordfromFile);
void PlayAgain();
void GameLogic(char *randomWordfromFile);
void clear_stdin();
void PlayGame();
int main()
{
printf("Welcome to Hangman. Would you like play? Please answer Y/N. \n");
int PlayorNot = getchar();
if (PlayorNot == 'Y' || PlayorNot == 'y')
PlayGame();
else
system("cls");
printf("Goodbye");
return 0;
}
void PlayGame()
{
char* word = GetWordFromFile();
GameLogic(word);
PlayAgain();
}
char* GetWordFromFile()
{
FILE* pointertoFile = NULL;
char randomWordfromFile[MAX_WORD_LEN];
int i = 0 , ran = 0;
srand(time(NULL));
pointertoFile = fopen("C:\\Users\\Aditya\\Dropbox\\Hangman\\hangman.txt" , "r+");
for(; fgets(randomWordfromFile , MAX_WORD_LEN, pointertoFile) ; i++)
;
ran = rand() % i;
rewind(pointertoFile);
for(i = 0 ; i < ran ; i++)
fgets(randomWordfromFile , MAX_WORD_LEN , pointertoFile);
return randomWordfromFile;
}
void GameLogic(char *randomWordfromFile)
{
int UserGuess;
int i, x;
int WrongGuesses;
size_t j;
size_t len = strlen(word);
char HiddenWord[len];
for (j = 0; j < len; ++j)
{
HiddenWord[i] = "_ ";
}
printf("%s", HiddenWord);
for(i = 0; i < MAX_TRIES; i++ )
{
printf("Go ahead and guess a letter\n");
clear_stdin();
scanf("%d", &UserGuess);
for (x = 0; x < len; x++)
{
if (randomWordfromFile[x] == UserGuess)
UserGuess = HiddenWord[x];
else
break;
}
}
printf("%s", randomWordfromFile);
}
void PlayAgain()
{
printf("Do you want to play again? Please answer with Yes/No?");
char PlayAgainAnswer = getchar();
if (PlayAgainAnswer == 'Y' || PlayAgainAnswer == 'y')
PlayGame();
else if (PlayAgainAnswer == 'N"' || PlayAgainAnswer == 'n')
printf("Thanks for playing");
else
printf("Thanks for playing");
}
void clear_stdin()
{
while( getchar() != '\n' ){;}
}
它最终编译后的工作和调试几天。出于某种原因,当我打印出来的字母不应该是。我相信它会进入第一个循环询问用户是否想玩。回答是,它会要求你猜一封信。但在要求它应该显示_ _ _之类之前,取决于单词中的字母数量。
我的猜测是问题出现在以下循环中:
for (j = 0; j < len; ++j)
{
HiddenWord[i] = "_ ";
}
printf("%s", HiddenWord);
我似乎无法在这个循环中发现问题,因为这是一个非常简单的循环。
答案 0 :(得分:2)
你在循环中使用j而i作为索引,你希望它们是相同的
答案 1 :(得分:1)
更改
char HiddenWord[len];
到
char* HiddenWord = (char*)malloc(len);
由于您希望阵列具有动态大小,因此您希望在运行时分配内存。 您还应该检查内存分配是否成功。看一下 http://www.programiz.com/c-programming/c-dynamic-memory-allocation并且在完成记忆后不要忘记释放记忆。
答案 2 :(得分:1)
i
vs j
HiddenWord[j] = '_';
,因为您正在分配一个字符HiddenWord[len] = '\0'
当然,数组应该长1个字符希望有所帮助
P.S。你可能想要这样的东西:
HiddenWord[2*j] = '_';
HiddenWord[2*j+1] = ' ';
但你明白了这一点:)