/****************************************************************************** * This program implements a simple number guessing game. * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ #undef NDEBUG #include "Utils.hpp" #include #include #include #include using namespace Utils; using namespace std; int main(int argc, char **argv) { // Get the maximum number. string input_str = Utils::prompt("Maximum for value: "); int max = Utils::stoiWithDefault(input_str, 10); if (max < 3) { cout << "That is too easy, using 10 instead." << endl; max = 10; } // Seed the pseudo-random number generator. srand(time(0)); rand(); rand(); rand(); rand(); rand(); // Compute a pseudo-random match value. int match_value = int(max * (rand()/(RAND_MAX + 1.0))) + 1; cout << "Try to guess the number I'm thinking of between 1 and " << max << endl; // Loop allowing the user to guess. int attempts = 1; while (true) { string const PROMPT_MSG = string("Guess #") + to_string(attempts) + string(": "); input_str = Utils::prompt(PROMPT_MSG); int guess = 0; try { guess = stoi(input_str); } catch (invalid_argument ex) { cout << "Your input makes no sense to me!" << endl; } if (guess != 0) { if (guess == match_value) { cout << "You guessed my number in " << attempts << " attempts!" << endl; break; } else if (guess < match_value) { cout << "Your guess is too low." << endl; } else { cout << "Your guess is too high." << endl; } ++attempts; } } return 0; }