I just started C++ a week ago. and i'm working on a guess number game. Everything works fine but the loop wont exit correctly. I wanted the loop to end after the user spent 5 guesses, and display "you've lost".
but unfortunately the loop won exit until the user guess it right. Please help!
Here's the source code:
#include <cstdlib>
#include <iostream>
#include <ctime> //2nd clock cpu
using namespace std;
int main(int argc, char *argv[])
{
cout << " We'll play a number guessing game \n";
cout << " Pick a number between 1 and 100. \n \n";
// notice the unsigned int for positive number only
/*why it's rand() %100 +1 where is this come from?
rand() is a class that generate a function, and 100 come from the
formula (max-min+1) 1. this is between 1-100, so 100-1 +1 =100,
then we add 100+1. so what the numPicked does is that
it will generate a random number between 1-100. */
srand((unsigned int)time(0)); //formula to seed the random number generator
unsigned int guessChance = 4; // store user input
int randNum = rand() % 100 +1; // exp1 = rand()%(max-min+1) +1
int guessNum; // stores the number of guesses
cout << "you have 5 chance to begin \n" ;
for (guessChance>1; guessNum!=randNum; guessChance--)
//here the for loop nesting begins.
{
cout << "Guess again to continue.. \n";
cin >>guessNum; //user input a number 1 to 100.
if (guessNum <randNum) //notice randNum is a
//random number generator
cout << "\nYou guessed too low!! \n \n"
<< "\nYou still have " << guessChance << " chance left. \n ";
else if (guessNum >randNum)
cout << "\nYou guessed too high! \n \n"
<< "\nYou still have "<< guessChance << " left \n";
//this is where the loops wont go the way i want
else if (guessChance<1) //wanted loop to end after 5 guesses
cout << "\n you've lost!";
}
//exit loops when the guess is right
cout << "\nYou guessed it!!! \nIt took you "
<< guessChance << " guesses to get it right." <<endl;