Greetings EeveryOne
You all know "Guess My Number" game when the computer chose a secret number and the player tries to guess it. This is my attempt to do the reverse as the player chose a secret number and the computer will try to guess it.
Code:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <limits>
#define FlushInput \
cin.clear();\
std::cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
using namespace std;
string MyToLower(string str);
int main()
{
int SecretNumb = 0;
int Tries = 0;
int Guess = 0;
int MinRange = 0;
int MaxRange = 100;
string Input = "";
string Hint = "";
bool WrongInput = true;
// Seed random number generator;
srand(static_cast<unsigned int>(time(0)));
cout << "\t\tComputer Guess My Number\n\n"
<< "Chose a number and the computer will try to guess it.\n"
<< "After each guess type either:\n\n"
<< "*too high: if the number guessed is higher than your secret number.\n\n"
<< "*too low : if the number guessed is lower than your secret number.\n\n"
<< "*right : if the number guessed is the same as your secret number.\n\n"
<< "\t------------------------------------------\n"
<< endl;
do
{
cout << "Please Enter A Secret Number "
<< "between 1 and 100: ";
cin >> Input;
FlushInput;
SecretNumb = atoi(Input.c_str());
if(isalpha(Input[0]) ||
SecretNumb < MinRange ||
SecretNumb > MaxRange )
{
cout << "Wrong Input.\n";
}
}while(isalpha(Input[0]) ||
SecretNumb < MinRange ||
SecretNumb > MaxRange );
do
{
//random between Max & Min inclusive:
//(ran()%(Max-Min+1))+Mix
Guess = (rand()%(MaxRange-MinRange+1))+
(MinRange);
cout << "My Guess Is: " << Guess
<< endl;
WrongInput = true;
while(WrongInput)
{
WrongInput = false;
cout << "Human's Hint: ";
getline(cin, Hint);
cout << endl;
if(MyToLower(Hint) == "too high")
{
if((Guess==SecretNumb))
cout << "Did You Forgot Your Secret Number,\nThe PC Already Guessed It!"
<< endl;
else MaxRange = Guess-1;
}
else
if(MyToLower(Hint) == "too low")
{
if((Guess==SecretNumb))
cout << "Did You Forgot Your Secret Number,\nThe PC Already Guessed It!"
<< endl;
else MinRange = Guess+1;
}
else
if(MyToLower(Hint) == "right")
{
Guess = SecretNumb;
}
else
{
cout << "Wrong Input." << endl;
WrongInput = true;
}
}
++Tries;
cout << "-----------------\n";
cout << "MaxRange = " << MaxRange << "\n";
cout << "MinRange = " << MinRange << "\n";
cout << "-----------------\n";
cout << endl;
}while(Guess!=SecretNumb);
cout << "Solved In " << Tries << " Tries."
<< endl;
return 0;
}
string MyToLower(string str)
{
int leng = str.length();
for(int i = 0; i<=leng; i++)
{
str[i] = tolower(str[i]);
}
return str;
}
I would like to hear your feedback and comments if any to improve my programming skills