-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberGuessing.cpp
More file actions
68 lines (53 loc) · 2.2 KB
/
Copy pathNumberGuessing.cpp
File metadata and controls
68 lines (53 loc) · 2.2 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <cstdlib> // For rand() and srand()
#include <ctime> // For time()
using namespace std;
int main() {
srand(static_cast<unsigned int>(time(0))); // Seed the random number generator
int secretNumber, userGuess, guessLimit, guessesTaken, totalWins = 0, totalLosses = 0;
char playAgain;
cout << "Welcome to the Number Guessing Game!" << endl;
cout << "You will have a limited number of guesses to find the secret number." << endl;
do {
secretNumber = rand() % 100 + 1; // Generate a random number between 1 and 100
guessLimit = 7; // Set the limit of guesses
guessesTaken = 0;
cout << "\nI'm thinking of a number between 1 and 100. You have " << guessLimit << " guesses." << endl;
bool hasWon = false;
while (guessesTaken < guessLimit) {
cout << "Enter your guess: ";
cin >> userGuess;
if (cin.fail()) {
cin.clear(); // Clear the error flags
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Discard the input
cout << "Please enter a valid number." << endl;
continue;
}
guessesTaken++;
if (userGuess < secretNumber) {
cout << "Too low. Try again." << endl;
}
else if (userGuess > secretNumber) {
cout << "Too high. Try again." << endl;
}
else {
cout << "Congratulations! You guessed the number in " << guessesTaken << " guesses!" << endl;
totalWins++;
hasWon = true;
break;
}
}
if (!hasWon) {
cout << "Sorry, you've run out of guesses. The number was " << secretNumber << "." << endl;
totalLosses++;
}
// Ask if the user wants to play again
cout << "Would you like to play again? (y/n): ";
cin >> playAgain;
cout << endl;
} while (playAgain == 'y' || playAgain == 'Y');
// Show win/loss record
cout << "Your win/loss record is: " << totalWins << " wins, " << totalLosses << " losses." << endl;
cout << "Thanks for playing!" << endl;
return 0;
}