Hi guys,
I was trying to write a guessing game program and encountered with an error that i am unable to resolve.
The code below is what i wrote for the game.But don't know why this code is not working at all.Please tell me where a went wrong.I am using visual studio express 2010 and orwell dev c++ with mingw 32
// Guessing_game.cpp:rs0
// Description:Allows a player to guess a secret number and shows the result.
#include<iostream>
#include<cstdlib>
#include<time.h>
usingnamespace std;
int main(){
int secret_num; //The range is 1 to 10.
int guess_num=0;
srand(time(NULL));
secret_num=(rand()%10) + 1;
do{
cout << "Enter your guess:";
cin >> guess_num;
if(!(cin>> guess_num)){
cout << "You entered a non-numeric character.Try again." << endl;
cin.clear();
cin.ignore(10000,'\n');
continue;
}
else {
if(secret_num > guess_num)
cout << "The entered number is too low from the secret number." << endl;
elseif(secret_num < guess_num)
cout << "The entered number is too high from the secret number." << endl;
}
}while(secret_num != guess_num);
cout << "The secret number is :" << secret_num << endl;
return 0;
}
@wesp its not an error as i have checked it and importantly i learned it from google's c++ educational material.You can check it too on your ide.But just after that if statement nothing is working.And i am completely clueless what went wrong.....
@arbitergoten the error is the program is asking me to enter my guess.and once i enter the number nothing happening at all.no more commands no exiting of function, nothing else.The cursor just keeps on blinking till i shut down the command prompt manually
if you remove line 16 you will get input by line 17, in fact you will get input two times with this code!
EDIT: I compile your code after make the changes(changes that arbitergoten said) and it now work correctly.
thank you all.actually all of you are right and i am wrong.And yes, after removing that line,my code is working perfectly.And can anyone please explain what logic i missed,because compiler did not showed any syntax error.
And sorry to @wesp who said me where i went wrong in one go.But i did not tried it...
What coder777 is saying is the if (!guess_num) or if(!(cin>> guess_num) would fail if the value entered is 0.
For example, a boolean variable can be True or False, but in terms of how it is stored in memory it is 0 (False) or 1 (True), so when you are doing your IF statements and the user enters 0, the program will assume that its False.
To extend on that, although a boolean 1 is true, we can use the same check to see if we are a value over 0, which is what your IF statements are doing.
1 2
if( // has the user entered a value higher than zero ){
cout << "You entered a non-numeric character.Try again." << endl;