// Guess A Number : C++ #include "stdafx.h" #include #include #include #include #include #include using std::stringstream; using std::cout; using std::cin; using std::endl; using std::string; using std::transform; using std::exception; bool IsAnInt(string input) { try { int output = atoi(input.c_str()); return true; } catch (exception &ex) { return false; } } int GetNumericInput(string prompt) { while (true) { cout << prompt << ": "; string ans; cin >> ans; if (IsAnInt(ans)) return atoi(ans.c_str()); cout << "Your entry was not a number." << endl; } } string GetInput(string question) { while (true) { cout << question << "?" << endl; string ans; cin >> ans; if (!ans.empty()) return ans; cout << "Your entry seems empty." << endl; } } bool AskToPlayAgain() { while (true) { string ans = GetInput("Would you like to play again? (\"YES\" or \"NO\")"); transform(ans.begin(), ans.end(), ans.begin(), ::toupper); if (ans == "YES" || ans == "Y") return true; if (ans == "NO" || ans == "N") return false; cout << "Please respond with \"YES\" or \"NO\"." << endl; } } void Run() { srand(time_t(0)); bool Running = true; bool GotMaxNumber = false; int MaxNumber = 0; int Answer = 0; bool GameOver = false; int Tries = 0; cout << "*** GUESS A NUMBER : C++ ***" << endl; while (Running) { while (!GotMaxNumber) { MaxNumber = GetNumericInput("Please enter the maximum number you wish to use"); if (MaxNumber > 0) { GotMaxNumber = true; Answer = rand() % MaxNumber; GameOver = false; Tries = 0; cout << "Ok, I am thinking of a number between 1 and " << MaxNumber << "." << endl; } else cout << "The maximum number should be greater than zero." << endl; } stringstream ss; ss << MaxNumber; string strMaxNumber = ss.str(); int Guess = GetNumericInput("Guess a number between 1 and " + strMaxNumber); Tries++; if (Guess > Answer) cout << "Too high." << endl; if (Guess < Answer) cout << "Too low." << endl; if (Guess == Answer) { GameOver = true; cout << "You got it in " << Tries << " "; if (Tries == 1) cout << "try!"; else cout << "tries!"; cout << endl; } if (GameOver) { Running = AskToPlayAgain(); if (Running) GotMaxNumber = false; } } cout << "Thanks for playing!" << endl << "*** GAME OVER ***" << endl; } int _tmain(int argc, _TCHAR* argv[]) { Run(); return 0; }