Reputation: 13
I'm trying to make a simple number guessing program with while loop but even after finding the right number (I changed the num with 5 and it didn't work) it does not exit the while loop. Can you tell me where the problem is?
int guess;
int num;
cout << "Enter the number (0-10): ";
cin >> guess;
while(guess != num){
int num = rand()%10;
cout << "Nope, keep trying." << endl;
cout << "Enter the number (0-10): ";
cin >> guess;
}
cout << "Congrats, you've found the number!" << endl;
Upvotes: 0
Views: 122
Reputation: 596307
The while
loop is evaluating a num
variable that is never assigned a value. The assignment being done inside the loop is to a different num
variable that shadows the outer variable of the same name.
Try this instead:
#include <iostream>
#include <limits>
#include <cstdlib>
using namespace std;
int main() {
int guess;
int num;
do {
cout << "Enter the number (0-10): ";
if (cin >> guess) {
if (guess == num)
break;
num = rand() % 10;
cout << "Nope, keep trying." << endl;
}
else {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Not a number, keep trying." << endl;
}
}
while (true);
cout << "Congrats, you've found the number!" << endl;
}
Upvotes: 0
Reputation: 234715
int num = rand() % 10;
is a declaration of a new variable num
within the loop body and that shadows the num
defined at the top of the program: while (guess != num)
is using the latter.
The solution is to write num = rand() % 10;
instead.
You will need to initialise num
to a value before attempting to read it, else technically the behaviour of your program is undefined. Consider reworking to a do
while
loop.
Upvotes: 5