2015-02-05 20 views
0

我一直在嘗試使用函數創建一個hang子手遊戲。一個讓用戶猜測,另一個功能是看用戶猜測是否在矢量中創建的單詞中。任何關於如何獲得玩家的幫助猜測以及如何創建一個函數來查看這個猜測是否是這個單詞將不勝感激。代碼如下。我將如何創建一個函數,以確定用戶輸入是否包含在向量中的單詞

char playersGuess();  

int main() 
{ 
//setup 
const int MAX_WRONG = 8; //maximum number of incorrect guesses allowed 

vector<string> words;  //collection of possible words to guess 
words.push_back("GUESS"); 
words.push_back("HANGMAN"); 
words.push_back("DIFFICULT"); 

srand(static_cast<unsigned int>(time(0))); 
random_shuffle(words.begin(), words.end()); 

const string THE_WORD = words[0];  //word to guess 
int wrong = 0;       //number of incorrect guesses 
string soFar(THE_WORD.size(), '-');  //words guessed so far 
string used = "";      //letters already guessed 

cout << "Welcome to Hangman 2. Good Luck!\n"; 

//main loop 
while ((wrong < MAX_WRONG && soFar != THE_WORD)) 
{ 
    cout << "\n\nYou have " << (MAX_WRONG - wrong); 
    cout << " incorrect guesses left.\n"; 
    cout << "\nYou've used the follwoing letters:\n" << used << endl; 
    cout << "\nSo far, the word is:\n" << soFar << endl; 
    char guess = playersGuess(); 
    while (used.find(guess) != string::npos) 
    { 
     cout << "\nYou've already guessed " << guess << endl; 
     playersGuess(); 
    } 

    used += guess; 

    if (THE_WORD.find(guess) != string::npos) 
    { 
     cout << "That's right! " << guess << " is in the word.\n"; 
     //update soFra to include newly guessed letter 
     for (int i = 0; i < THE_WORD.length(); ++i) 
     { 
      if (THE_WORD[i] == guess) 
      { 
       soFar[i] = guess; 
      } 
     } 
    } 
    else 
    { 
     cout << "Sorry. " << guess << " isn't in the word.\n"; 
     ++wrong; 
    } 
} 

//shut down 
if (wrong == MAX_WRONG) 
{ 
    cout << "\nYou've been hanged!"; 
} 
else 
{ 
    cout << "\nYou guessed it!"; 
} 

cout << "\nThe Word was " << THE_WORD << endl; 

return 0; 
} 

char playersGuess() 
{ 
char guess; 
cout << "\n\nEnter your guess: "; 
cin >> guess; 
guess = toupper(guess);  //make uppercase since secret word in uppercase 
return guess; 
} 

回答

1

您可以使用string::find來搜索string特定char

char guess; // assume this is already set 
std::string answer // this too 

if (answer.find(guess) != std::string::npos) 
{ 
    // Correct letter! 
} 
else 
{ 
    // They were wrong, add a body part 
} 

你的代碼是不工作的原因是因爲你自己的猜測分配給任何變量。 guess是隻存在於playersGuess內的局部變量。你必須做

char guess = playersGuess(); 
while (used.find(guess) != string::npos) 
{ 
    // ... 
+0

謝謝我指派玩家猜測一個變量,它現在的作品。但是我仍然在努力創造一個函數來檢查玩家猜測哪裏是正確的。 – 2015-02-05 19:35:25

1

你需要做的事情與返回playersGuess()。你輸入一個字符,但然後有效地扔掉它:

char guess = playersGuess(); 
// ^^^^^ 
while (used.find(guess) != string::npos) 
{ 
    cout << "\nYou've already guessed " << guess << endl; 
    guess = playersGuess(); 
// ^^^^^ 
} 
+0

我將如何去使用函數中的string :: find。 – 2015-02-05 19:37:48

相關問題