您将需要学习创建小型的单一用途功能并将它们组合在一起。
#include <set> // because you have a set of targets...
#include <string> // used to represent a target
using Target = std::string;
static Target const MissedTarget = "";
static bool isGuessCorrect(Target const& guess,
std::set<Target> const& targets)
{
return targets.count(guess);
}
// Returns the target hit (if any), or MissedTarget otherwise
static Target tryOnce(std::set<Target> const& targets) {
std::cout << "Enter in a coordinate between A-1 and D-4 (i.e. C4): ";
std::string guess;
if (std::cin >> guess) {
if (isGuessCorrect(guess, targets)) { return guess; }
return MissedTarget;
}
// Something that could not (unfortunately) be parsed,
// we need to clear std::cin
std::cin.clear();
std::cin.ignore(std::numeric_limit<size_t>::max(), '\n');
return MissedTarget;
}
static bool tryFewTimes(size_t const tries, std::set<Target>& targets) {
for (size_t n = 0; n != tries; ++n) {
Target const target = tryOnce(targets);
if (target == MissedTarget) {
std::cout << "Missed! Try again!\n";
continue;
}
targets.erase(target);
std::cout << "Congratz! You got " << target
<< "! Only " << targets.size() << " remaining\n";
return true;
}
std::cout << "You flunked it, can't always win :(\n";
return false;
}
int main() {
std::set<Target> targets = { "A1", "B1", "C1" };
while (not targets.empty() and tryFewTimes(3, targets)) {}
}