I wrote a really basic game that makes the user guess a number between 1 and 100 to practice using loops (just started learning them), but when the correct number is entered the loop keeps running. Thoughts?
#include <iostream>
usingnamespace std;
void guessTooHigh() //output is guess is too high
{
cout << "You're guess was too high\n" << endl;
}
void guessTooLow()
{
cout << "Your guess was too low\n" << endl; //output is guess is too low
}
void guessCorrect()
{
cout << "Well done, you guessed correctly\n" << endl; //output is guess is correct
}
int main()
{
int aim = 32; //number that the user aspires to guess
int x; //introducing the value so the while loop knows to look for it
while (x != aim) //keep asking for a guess whilst the guess does not equal the aim (32)
{
cout << "Please enter an integer between 0 and 100" << endl; //ask for guess
int x;
cin >> x;
if (x < aim)
{
guessTooLow();
}
elseif (x > aim)
{
guessTooHigh();
}
else
{
guessCorrect();
}
}
return 0;
}
don't use break there. your logic is correct (while x != aim) the loop keeps going on, when they're equal the loop finishes.
the problem is that you declare the int x twice, out of the main loop and again inside it.
the outer x is used in the line "while (x != aim)", and the inner x is used in your if-else statments. you're confusing the scopes of two integeres who have the same name - 'x'.
long story short: remove line 27 and it should work.