-
number guessing game
i am new to c++ but i know some other languages. I have been programming in c++ for about 5 hrs now and i am having a problem with my program. when i guess for the first time it is like it doesn't count. no matter what i type it will tell me that my guess is too low. can anyone help me?
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
long guess = 0, x = 0;
const long MAX = 500, MIN = 1;
srand(time(NULL));
x = (rand() % (MAX - MIN + 1)) + MIN;
while (guess != x)
{
cout<< endl;
cout<<"Enter a number between 1 and 500" << endl;
cin.ignore();
cin>> guess;
cout<<"The secret number is " << x;
if (guess < x) {
cout<<"You was too low, Try again"; }
else if ( guess > x) {
cout<<"You was too high, Try again";}
else {
cout<<"Invalid guess";}
}
}
-
Re: number guessing game
What is the purpose of cin.ignore()? That is probably what is wrong with your code. Try removing it and see what happens.
Also try printing out the guess:
Code:
if (guess < x){
cout << "Your guess (" << guess << ") was too low, Try again" << endl; }
else if ( guess > x){
cout << "Your guess (" << guess << ") was too high, Try again" << endl; }
else{
cout << "Invalid guess (" << guess << ")" << endl; }
}