Hi! For a class that I am taking we are supposed to make a guessing game that creates a random number between 1 and 1000 and we have to guess it.
I have used all the parts that we have learned in the class already.
But for some reason the game replays even if I type "n" which is supposed to be No and supposed to continue to say "Press any key to exit..." then exit
Run it in a debugger or add temporary code to print the value of replay. I think you'll find that replay is the newline character after the final guess rather than the letter that they enter. Try making replay a string instead and check the first character.
What dhayden is hinting at:
After doing integer input with cin >> guess there is an extra invisible character leftover in the input stream that cin uses behind the scenes. Simply add cin.ignore(); after every cin >> guess; to remove leftovers. This really only matters when you swap back and forth between integer inputs and char inputs.
Here is the new code... It still doesnt seem to want to work :(
When "y" or "Y" is entered for "Would you like to play again?" It still says "Thanks for playing!" When Its supposed to restart the game
cout << "Would you like to play again? Y/N: "; // ask them if they want to play again
cin >> replay; // get their input
cout << "\n\n";
if (replay == 'y' || replay == 'Y') // if they input "Y", indicating they DO want to play again
{
again = false; // <- you set again to FALSE, signaling the program to close
cout << "Thanks for playing!" <<endl;
break;
}
Now that I look more closely it looks like the OP wanted to check for "N" in the first place. (Since it was originally replay != 'y')
So perhaps changing 'y' -> 'n' and 'Y' -> 'N' would keep the logic of the body of the if statement the same.
Also I noticed some of the game initialization statements need to be moved into the body of the do-while loop otherwise the user will be guessing the same random number for every game.