/****************************************************************************** * This program implements a simple number guessing game. * * Copyright © 2021 Richard Lesh. All rights reserved. *****************************************************************************/ #include "Utils.hpp" #include #include #include #include using namespace std; int main(int argc, char **argv) { // Get the maximum number. string inputStr = Utils::prompt("Maximum for value: "); int max = Utils::stoiWithDefault(inputStr, 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 matchValue = 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 promptMsg = "Guess #" + to_string(attempts) + ": "; inputStr = Utils::prompt(promptMsg); int guess = 0; try { guess = stoi(inputStr); } catch (invalid_argument ex) { cout << "Your input makes no sense to me!" << endl; } if (guess != 0) { if (guess == matchValue) { cout << "You guessed my number in " << attempts << " attempts!" << endl; break; } else if (guess < matchValue) { cout << "Your guess is too low." << endl; } else { cout << "Your guess is too high." << endl; } ++attempts; } } return 0; }