#include #include #include //for chrono::system_clock #include //for default_random_engine #include //for bind using namespace std; int main() { cout << "I am thinking of a number in the range 1 to 100 inclusive.\n" << "Keep trying until you guess it.\n\n"; //The value of the expression r() will be a random int in the range //1 to 100 inclusive. unsigned seed = chrono::system_clock::now().time_since_epoch().count(); default_random_engine engine {seed}; uniform_int_distribution distribution {1, 100}; auto r {bind(distribution, engine)}; const int correct {r()}; int guess_count {0}; for (;;) { //Looks like an infinite loop, but it isn't. cout << "Go ahead: "; int guess {0}; cin >> guess; ++guess_count; // Increment the counter for each guess if (!cin) { cerr << "Sorry, that wasn't a number.\n"; return EXIT_FAILURE; } if (guess == correct) { break; //out of the for loop. A test in the middle. } //Give the user a hint. if (guess < correct) { cout << "Too low."; } else { cout << "Too high."; } cout << " Try again.\n\n"; } //Arrive here after the break. cout << "That's right, the number was " << correct << ".\n"; // Print the number of guesses if (guess_count == 1) { cout << "It only took you " << guess_count << " guess!\n"; } else { cout << "It took you " << guess_count << " guesses!\n"; } return EXIT_SUCCESS; }