我很難搞清楚如何讓這個Hangman程序根據用戶輸入選擇正確的數組。雖然我意識到我可以很容易地設置一個包含相同代碼的不同if
語句,但這似乎是不必要的內存使用量。所以我的問題是這樣的:我可以使用指針(或者,最好是簡單些)來表示數組名稱,這樣我只需要一個代碼序列?我試圖通過指針做到這一點,但我相信我錯了,所以如果有人有任何提示,我會非常感激。使用不同數組的指針?
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
int main(){
char easy_animals[2][3] = {
{ 'c', 'a', 't' }, //0
{ 'd', 'o', 'g' }, //1
};
char easy_names[2][3] = {
{ 'p', 'a', 't' }, //0
{ 'b', 'o', 'b' }, //1
};
char u,
newline,
dis[16] = { '_', '_', '_', '_' };
input[10];
int random,
guesses = 3,
finish = 0;
_Bool successfulGuess = false;
srand(time(NULL));
random = rand() % 13;
printf("Animals or names?\n");
gets(input);
if (input[0] == 'a'){ // Or any other letter to signify the correct subject
printf("Animal %d\n", random); // Check random number
printf("---------\n\n");
while (guesses > 0){
finish = 0;
successfulGuess = false;
printf("Enter a letter: ");
u = getchar();
newline = getchar();
for (int i = 0; i < 3; i++){
if (u == dis[i]){
successfulGuess = true;
printf("\nYou already guessed this letter.\n");
printf("\ninput = dis[i]\nGuesses left: %d\n\n", guesses);
break;
}
else if (easy_animals[random][i] == u){
successfulGuess = true;
dis[i] = u;
printf("\ninput = array char\nGuesses left: %d\n\n", guesses);
}
}
printf("\n");
for (int i = 0; i < 3; i++){
printf("%c", dis[i]);
}
if (successfulGuess == false){
guesses--;
printf("\n\nbool statement\nGuesses left: %d\n\n", guesses);
}
if (guesses == 0){
printf("Sorry, you've run out of guesses.");
}
for (int i = 0; i < 3; i++) {
if (dis[i] != '_') {
finish++;
}
if (finish == 3){
printf("\n\nYou guessed the word!");
guesses = 0;
}
else{
continue;
}
}
printf("\n\n");
}
}
system("pause");
}
*您這有可能:
最後,確定用戶是否已經取得了成功的猜測時使用您的新指針一個指針「開關」,但是:函數?或者也許另一個數組維度? – deviantfan 2014-10-03 21:09:32