Okay when I compile and run this program with a negative integer in the list of integers, it works fine. When I use only one number or a series of positive integers, it keeps repeating until it has a run-time error. I wrote this in notepad++ and use ideone.com to compile and test the code.
What do I need to do to fix it? Also is my first while loop when initializing my variables, and setting up the number generator even necessary?
CODE:
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main()
{
while(true) { // This is the main loop.
// Initialize
int randomNumber; // Integer for system number.
int guess; // User guess is stored in here.
int tries; // Counter for number of tries is stored here.
srand(time(0)); // To generate a new number.
randomNumber = rand ( )%100 + 1; // System number is stored here.
tries = 0; // The amount of attempts will be counted with this.
while(true) { // Get user number loop.
// Get number.
cout << "Guess a number between 1 and 100, or enter a negative integer to exit. " ;
cin >> guess;
cin.ignore();
// Check if user enters negative number to exit.
if(guess <= 0) {
cout << "You have chosen to stop playing.\n ";
break;
}
// Check number.
if(guess > randomNumber) {
cout << "Too high, Try again.\n";
} elseif(guess < randomNumber) {
cout << "Too low, Try again.\n";
} else {
break;
}
// If not correct number, increment tries.
tries++;
}
// Check for correctness of tries.
if(randomNumber == guess) {
cout << "Congratulations you guessed correctly!" ;
cout << "It took you " << tries << " tries." ;
} else {
cout << "It took you " << tries << " tries." ;
cin.ignore();
}
return 0;
}
}