Can anyone help create a limit of guesses for my code?

I am trying to limit the number of guesses in this random number guessing program to 5. I have everything working except that it doesn't display the "you lost!" after 5 guesses. My code is below if anyone has any suggestions.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;


#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
constexpr int MaxTries {5};
int guess {}, tries {};
std::srand(static_cast<unsigned int>(time(nullptr)));
const auto number {rand() % 50 + 1}; // number between 1 and 50

do {
std::cout << "Enter a guess between 1 and 50: ";
std::cin >> guess;
++tries;

if (guess < number)
std::cout << "Your guess is low\n";
else if (guess > number)
std::cout << "Your guess is high\n";
else
std::cout << "You guessed it right!!!\n";
} while (guess != number && tries != MaxTries);

if (guess != number)
std::cout << "You lost!!!\n";

Last edited on
You need to check the tries in you loop. Like so:

} while ((guess != number) && (tries < 5));
Perhaps:

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
#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
	constexpr int MaxTries {5};
	int guess {}, tries {};
	std::srand(static_cast<unsigned int>(time(nullptr)));
	const auto number {rand() % 50 + 1}; // number between 1 and 50

	do {
		std::cout << "Enter a guess between 1 and 50: ";
		std::cin >> guess;
		++tries;

		if (guess < number)
			std::cout << "Your guess is low\n";
		else if (guess > number)
			std::cout << "Your guess is high\n";
		else
			std::cout << "You guessed it right!!!\n";
	} while (guess != number && tries != MaxTries);

	if (guess != number)
		std::cout << "You lost!!!\n";
}

Oh I see how to fix it now. Thanks for the help!
Topic archived. No new replies allowed.