【发布时间】:2020-07-18 05:34:01
【问题描述】:
char playAgain;
do
{
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(), '-'); //word guessed so far
string used = ""; //letter alrdy guessed
cout << "Welcome to Hangman. Good luck!\n";
while ((wrong < MAX_WRONG) && (soFar != THE_WORD))
{
cout << "\n\nYou have " << (MAX_WRONG - wrong);
cout << " incorrect guesses left.\n";
cout << "\nYou've used the following letters:\n" << used << endl;
cout << "\nSo far, the word is:\n" << soFar << endl;
char guess;
cout << "\n\nEnter you guess: ";
cin >> guess;
guess = toupper(guess); //make uppercase since secret word in uppercase
while (used.find(guess) != string::npos)
{
cout << "You've already guessed " << guess << endl;
cout << "Enter you guess: ";
cin >> guess;
guess = toupper(guess);
}
used += guess;
if (THE_WORD.find(guess) != string::npos)
{
cout << "That's right! " << guess << " is in the word.\n";
//update soFar 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;
cout << "\nPlay again? < Y , N >\n";
cin >> playAgain;
} while ((playAgain == 'Y') || (playAgain == 'y'));
return 0;
您好,我已经尝试让这款游戏成为一款可重复的游戏。我成功了,但注意到当玩家选择 Y 或 y 时游戏只会循环一次。这显然是因为 playAgain 现在保留了该值。我该如何解决这个问题,以便 playAgain 在游戏再次开始时“忘记”用户输入的内容?感谢您的帮助。
【问题讨论】:
-
不相关:
srand(static_cast<unsigned int>(time(0)));应该只执行 一次 - 将它移到循环之前,就在程序的开头。 -
注意:
random_shuffle在 C++14 中被弃用,在 C++17 中被移除。请改用shuffle。另外,请发送minimal reproducible example。 -
playAgain = 'n';在循环的顶部?读取单个char非常脆弱,如果存在额外的无关字符(例如输入"yes"而不是'y'),则在每个输入之后考虑std::basic_istream::ignore。您的输入没有任何明显错误。 -
感谢大家的cmets,大约一个月前我刚刚开始自己学习C++,这本书显然有点过时了。我可能会继续读完这本书以理解这些概念并继续学习现代在线教程。
标签: c++ loops while-loop