bool out_of_guesses = false;
должно быть между while(true)
и while(animal != guess && !out_of_guesses)
, а не за пределами первого цикла while.Поскольку наше условие цикла while всегда ложно, а затем оно входит в него.
Вы также должны сбросить переменную guess
между этими двумя циклами, иначе может произойти то же самое (false, в то время как цикл) в случаеответа найден.
Здесь приведен код с некоторым рефакторингом / рецензией, который я использовал в качестве заглавной буквы для обработки любой типографии ответа.Я также удалил переменную вне догадки, чтобы использовать счетчик и ограничить его.
#include <iostream>
#include <string>
#include <cctype>
int main()
{
const std::string animal = "FISH";
const int limit = 5;
do
{
std::cout << "I am thinking of an animal.\n";
int count = 0;
std::string guess;
while(animal.compare(std::toupper(guess)) != 0 && count < limit)
{
std::cout << "Can you guess what animal I am thinking of?: \n";
std::cin >> guess;
count++;
if(animal.compare(std::toupper(guess)) != 0)
{
std::cout << "\nHmm, nope. That's not the animal I'm thinking of.\n";
if(count > 2)
{
std::cout << "I'll give you a hint. It lives in water.\n";
}
}
}
}//End nested while loop
if(count >= limit)
{
std::cout << "\nI'm sorry, but you are out of guesses.\n";
}
else
{
std::cout << "\n*** Good job! You guessed the correct animal! ***\n";
std::cout << "\t\t><)))º> ❤ <º)))><\t\t\n";
}
char choose = 'Y' ;
std::cout << "Would you like to try again?(y/n): ";
std::cin >> choose;
if(std::toupper(choose) == 'N') break;
} while(true);
return 0;
}