Guess number 1-500

Can anyone tell me where I went wrong? One error code says i can use the "break" because it's not in a loop but I though it was? And another issue im having is when I run on previous attempts, my number is not random, how do i use the srand or rand function. Help! thank you!

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
while (true)
// Main loop.
// Initialize and allocate.
srand((unsigned)time(0));
int number = rand(); // 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.

while (true)
{ // Get user number loop.
// Get number.
cout << "Enter a number between 1 and 500 (" << tries++ << " tries ): ";
cin >> guess;
cin.ignore();
}

// Check number.
if (guess > number)
{
cout << "Too high! Try again.\n";
}
else if (guess < number)
{
cout << "Too low! Try again.\n";
}
else if (guess == number)
{
cout << "Congratulations!! " << endl;
cout << "You got the right number in " << tries << " tries!\n";
break;
}

return 0;
}
With your code properly indented, it is clear to see that your first while loop has only one line inside it (USE BRACES), and your break statement is not inside any loops.

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
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
  while (true)
    // Main loop.
    // Initialize and allocate.
    srand((unsigned)time(0));  // THIS IS THE ONLY LINE INSIDE THE FIRST WHILE LOOP
  int number = rand(); // 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.

  while (true)
    { // Get user number loop.
      // Get number.
      cout << "Enter a number between 1 and 500 (" << tries++ << " tries ): ";
      cin >> guess;
      cin.ignore();
    }

  // Check number.
  if (guess > number)
    {
      cout << "Too high! Try again.\n";
    }
  else if (guess < number)
    {
      cout << "Too low! Try again.\n";
    }
  else if (guess == number)
    {
      cout << "Congratulations!! " << endl;
      cout << "You got the right number in " << tries << " tries!\n";
      break;  // THIS IS CLEARLY NOT INSIDE ANY WHILE LOOPS
    }

  return 0;
} 

If I am reading the code correctly, then it looks like an infinity while loop that constantly seeds random...
Thank you for the replies!
Topic archived. No new replies allowed.