forked from The-Open-Source-Summit/Secret_Number_Guess_Game
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
51 lines (40 loc) · 1.51 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <limits>
using namespace std;
int main() {
srand(time(0));
const int minNumber = 1;
const int maxNumber = 100;
char playAgain;
do {
int secretNumber = rand() % (maxNumber - minNumber + 1) + minNumber;
int attempts = 0;
int guess;
cout << "Welcome to the Number Guessing Game!" << endl;
cout << "I'm thinking of a number between " << minNumber << " and " << maxNumber << "." << endl;
while (true) {
cout << "Enter your guess: ";
if (!(cin >> guess)) {
cout << "Invalid input. Please enter a valid number." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
continue;
}
attempts++;
if (guess < secretNumber) {
cout << "Too low! Try again." << endl;
} else if (guess > secretNumber) {
cout << "Too high! Try again." << endl;
} else {
cout << "Congratulations! You guessed the number in " << attempts << " attempts." << endl;
break;
}
}
cout << "Do you want to play again? (Y/N): ";
cin >> playAgain;
} while (playAgain == 'Y' || playAgain == 'y');
cout << "Thanks for playing! Goodbye." << endl;
return 0;
}