### How to limit number of guesses on a program.

Hey, so I've created a random number game where you are supposed to guess the number. The only problem is I want the user to only have five guesses, but I can't figure out how to do that. Any suggestions? (By the way, the program as of right now is set to print what the number is, that is just so that I know it works)

Here is my current code.

 ``1234567891011121314151617181920212223242526272829303132333435363738`` ``````#include /*included to allow for cout/cin to be used*/ #include /*included to allow time() to be used*/ #include /*include to allow rand() and srand() to be used*/ using namespace std; int main() { bool cont=true; while(cont) { int count=0; int guess; srand(time(0)); /*seeds random number generator. Do this just once*/ int x = rand() % 50; cout << "I'm thinking of a number between one and fifty. You have five tries. Go."; cout << "\nx = " << x << endl; std::cin >> guess; while (guess !=x) { { if (guess > x) { cout << "Too high! Try again. "; cin >> guess; } if (guess < x) { cout << "Too low! Try again. "; cin>>guess; } if (guess == x) { cout << "You're exactly right! Good job! \n"; return 0; } } } } return 0; }``````

Thank you for any help.
Last edited on
Use an int to count how many guesses they've had, add one each time it loops, exit the loop when they have had too many guesses.
Hmm. I tried doing that, maybe I'm doing it wrong. This is what I added (right at the start of the while loop).

However, when I run it after it asks for my first guess, inputting guesses doesn't do anything.

 ``123456`` ``````count++; if (count ==5) { cout << "Sorry, you're out of guesses!"; return 0; }``````
 ``123456789101112131415161718`` `````` while (guess !=x && count!=5) { count++; if (guess > x) { cout << "Too high! Try again. "; cin >> guess; } else if (guess < x) { cout << "Too low! Try again. "; cin>>guess; } else { cout << "You're exactly right! Good job! \n"; } }``````
Oh I figured it out!

 ``1234567891011121314151617181920212223`` ``````while (guess !=x && count<5) { if (guess > x) { cout << "Too high! Try again. "; cin >> guess; count++; } if (guess < x) { cout << "Too low! Try again. "; cin>>guess; count++; } if (guess==x) { cout << "You're exactly right! Good job! \n"; return 0; } if (count==5) { cout << "You're out of guesses!\n"; return 0; } }``````
Last edited on
Do you initialize count to 0 before entering the loop?

e: oh nevermind. You should get a new guess at the beginning of the loop. You're getting new guesses in the middle of the loop. (cin >> guess;). And the way you handle it (if, if, if, instead of if, else if, else if.) it's possible to have a guess that's higher than x, then one that's lower than x, in one single loop.
Last edited on
Oh okay that actually helped a lot. I switched it around and put the guess at the start of the loop, and changed it from all if's to if, else if, else if. Thank you very much!
Topic archived. No new replies allowed.