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;
}
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.
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main()
{
while (true)
// Main loop.
// Initialize and allocate.
srand((unsigned)time(0)); // THIS IS THE ONLY LINE INSIDE THE FIRST WHILE LOOPint 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";
}
elseif (guess < number)
{
cout << "Too low! Try again.\n";
}
elseif (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;
}