Hello. Here is your fixed code with comments:
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 69 70 71 72 73 74 75 76 77
|
#include <iostream>
#include <cstdlib>
#include <ctime>
int main(void) {
srand(time(NULL)); // To not have the same numbers over and over again.
while(true) { // Main loop.
// Initialize and allocate.
int number = rand() % 99 + 2; // System number is stored in here.
int guess; // User guess is stored in here.
int tries = 0; // Number of tries is stored here.
char answer; // User answer to question is stored here.
//std::cout << number << "\n"; // Was used for debug...
while(true) { // Get user number loop.
// Get number.
std::cout << "Enter a number between 1 and 100 (" << 20 - tries << " tries left): ";
std::cin >> guess;
std::cin.ignore();
// Check is tries are taken up.
if(tries >= 20) {
break;
}
// Check number.
if(guess > number) {
std::cout << "Too high! Try again.\n";
} else if(guess < number) {
std::cout << "Too low! Try again.\n";
} else {
break;
}
// If not number, increment tries.
tries++;
}
// Check for tries.
if(tries >= 20) {
std::cout << "You ran out of tries!\n\n";
} else {
// Or, user won.
std::cout<<"Congratulations!! " << std::endl;
std::cout<<"You got the right number in " << tries << " tries!\n";
}
while(true) { // Loop to ask user is he/she would like to play again.
// Get user response.
std::cout << "Would you like to play again (Y/N)? ";
std::cin >> answer;
std::cin.ignore();
// Check if proper response.
if(answer == 'n' || answer == 'N' || answer == 'y' || answer == 'Y') {
break;
} else {
std::cout << "Please enter \'Y\' or \'N\'...\n";
}
}
// Check user's input and run again or exit;
if(answer == 'n' || answer == 'N') {
std::cout << "Thank you for playing!";
break;
} else {
std::cout << "\n\n\n";
}
}
// Safely exit.
std::cout << "\n\nEnter anything to exit. . . ";
std::cin.ignore();
return 0;
}
|
Some things I needed to fix:
1. Line 2 is useless.
2. Line 3 is not a good coding practice.
3. Line 13: Number is undefined, thus resulting in undefined behaviour. Also you need to include cstdlib for srand.
4. Line 16: You keep changing the number every loop!
5. Line 21: You keep setting tries to 1 when you are supposed to increment it.
6. Lines 23 & 24: Move this inside the loop, you need to check for all possibilities.
7. Line 22: So if the guess is higher, we break? How about if it is lower?
8. Line 32: You are just checking 'N' with true, which will always return false. You need to check 'N' against the user response.
9. Line 34: This loop will keep going until the user presses 'N'. This is bad because if the user wants to play again, he/she cannot because this loop does not acknowledge that.
10. Line 38: The user has no idea what to do. Tell the user what to do!