Mar 19, 2011 at 12:51pm UTC
Hi guys! Im working on a very simple guessing game using a random number generator, the problem is that I wanted to give the choice of different difficulty levels and with this comes the problem. When I run the game the secret number never comes up....ex. I have to guess between 1-100, i type 54, game says too small, I type 55, game says too big etc....
I've just started so I'll probably figure it out but thought maybe someone could give me a hint.
Appreciate any help.
/Guessing_Game
#include <iostream>
#include <string>
#include <ctime>
#include <iomanip>
using namespace std;
int main ()
{
string name, gender;
int guess, age, secret_number, level;
srand((unsigned)time(0));
cout << "\n\t\t The Guessing Game!"
<< "\n\t\t ==================";
cout << "\n\nEnter name: ";
getline (cin, name);
cout << "\n" << name << ", please enter your age: ";
cin >> age;
cout << "\nEnter Gender (M/F): ";
cin >> gender;
cout << "\nPlayer Profile!"
<< "\n------------------";
cout << "\nName: " << name;
cout << "\nAge: " << age;
cout << "\nGender: " << gender
<< "\n------------------"
<<"\n\n";
cout << "\nPlease choose difficulty level. "
<< "\n(1) Easy."
<< "\n(2) Medium."
<< "\n(3) Hard."
<< "\nInput: ";
cin >> level;
if (level == 1)
{
do{
secret_number = rand () % 20 + 1;
cout << "\nGuess a number between 1-20: ";
cin >> guess;
if (guess < secret_number)
cout << "\nToo small, try again!\n\n";
else if ( guess > secret_number)
cout << "\nToo big, try again!\n\n";
else
cout << "\nWell done, you guessed it!\n\n";
}while (guess != secret_number);
}
else if (level == 2)
{
do{
secret_number = rand() % 100 + 1;
cout << "\nGuess a number between 1-100: ";
cin >> guess;
if (guess < secret_number)
cout << "\nToo small, try again!\n\n";
else if ( guess > secret_number)
cout << "\nToo big, try again!\n\n";
else
cout << "\nWell done, you guessed it!\n\n";
}while (guess != secret_number);
}
else if (level == 3)
{
do{
secret_number = rand() % 500 + 1;
cout << "\nGuess a number between 1-500: ";
cin >> guess;
if (guess < secret_number)
cout << "\nToo small, try again!\n\n";
else if ( guess > secret_number)
cout << "\nToo big, try again!\n\n";
else
cout << "\nWell done, you guessed it!\n\n";
}while (guess != secret_number);
}
else
cout << "\nInvalid input!!\n\n";
system ("pause");
return 0;
}
Mar 19, 2011 at 2:04pm UTC
you secret_number is generated in the do-while-loop. so before every input a new one is generated.
Mar 19, 2011 at 2:06pm UTC
secret_number = rand () % 20 + 1;
Put this out of loop.
Mar 19, 2011 at 2:14pm UTC
Thanks :)....it was so simple, can't believe I didn't se it.