2014-10-03 19 views
-1

我很難搞清楚如何讓這個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"); 
} 
+0

*您這有可能:

if (/*user selects "animals"*/) { wordToGuess = easy_animals[random]; } else if (/*user selects "names"*/) { wordToGuess = easy_names[random]; } else (/*input is invalid*/) { // Prompt the user to re-enter his/her choice. } 

最後,確定用戶是否已經取得了成功的猜測時使用您的新指針一個指針「開關」,但是:函數?或者也許另一個數組維度? – deviantfan 2014-10-03 21:09:32

回答

0

easy_animalseasy_names是指向char的兩個陣列。選擇一個單詞,用戶將不得不猜測僅僅意味着選擇這些指針之一,因此宣佈自己char*,你可以用它來表示字:

char* wordToGuess; 

然後從相關分配給隨機選擇的指針數組像這樣:

else if (wordToGuess[i] == u){ 
    successfulGuess = 1; 
    dis[i] = u; 
    printf("\ninput = array char\nGuesses left: %d\n\n", guesses); 
} 
+0

這似乎沒有說明for循環使用我來檢查數組的每一列。當我輸入一個匹配的字母(即麋鹿中的「e」)時,它會打印出「eee」,然後告訴我我贏了比賽。 – Novaea 2014-10-03 21:47:35

+0

我上面提出的建議並不會產生這種行爲 - 我使用這些更改運行程序,「麋鹿」運行正常 - 所以您必須在其他地方有另一個問題。 – 2014-10-03 22:42:29