Oct 15, 2008 at 1:36am UTC
Well, I in my PlayGame() function, if you guess the correct number, the bool variable, 'Victory' is set to true. But even though it IS being set to true, my if statement is thinking it is false! Here is the code:
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
void PlayGame()
{
int UserTries = 10;
int UserGuess = 0;
int SecretNumber = rand() % 10 + 1;
string HigherLower;
bool Victory = false ;
system("CLS" );
cout << "Try to Guess the Number! (1-10): " ;
cin >> UserGuess; cin.sync();
cout << endl << endl;
while ( UserTries > 0 && UserGuess != SecretNumber && Victory == false ) {
if ( UserGuess > SecretNumber ) {
HigherLower = "Lower" ;
}
else if ( UserGuess < SecretNumber ) {
HigherLower = "Higher" ;
}
else if ( UserGuess == SecretNumber ) {
Victory = true ;
}
system("CLS" );
cout << "(" << HigherLower << ") (Last Guess: " << UserGuess << ")" << endl;
cout << "> " ;
cin >> UserGuess; cin.sync();
UserTries--;
}
if ( Victory == true ) {
cout << "Congratulations! You won!" ;
CURRENT_BALLANCE++;
}
else if ( Victory == false ) {
cout << "You lost. " ;
CURRENT_BALLANCE--;
}
cin.get();
}
Instead of printing, 'Congratulations! You won!' , it prints, 'You lost.' even when I guess the correct number. Any idea why that is?
Last edited on Oct 15, 2008 at 1:37am UTC
Oct 15, 2008 at 4:15am UTC
It's because on your while loop, if they guess the correct number, the program never enters the loop to set victory to true, therefore making it always false.
Oct 15, 2008 at 10:07pm UTC
So should I remove the 'Victory == false' condition and add a 'break;' in my else if statement?
Oct 16, 2008 at 12:18am UTC
I would just move it to below where they guess, so it is actually set before the program gets out of the while loop.