#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
usingnamespace std;
int main()
{
srand(static_cast<unsignedint>(time(0))); //seed random number generator
int compGuess = rand() % 100 + 1; // random number between 1 and 100
int tries = 0;
int answer;
bool guess;
int lo=1;
int hi=100;
char nothing;
bool test;
cout<<"\tWelcome to Guess your Number!\n";
cout<<"\tThink of a number between 1 and 100.\n\n";
do
{
cout<<"My guess is "<<compGuess <<"\n";
cout<<"Is this: \n";
cout<<"1: Too low\n";
cout<<"2: Too high\n";
cout<<"3: correct\n";
cout<<"Your input: ";
cin>>answer;
cout<<"\n";
++tries;
guess = false;
while(cin.fail() || answer < 1 || answer > 3)
{
cout<<"Please enter a valid input!\n";
cout<<"Your input: ";
cin.clear();
cin.get();
cin>>answer;
cout<<"\n";
}
if (answer !=3 && (hi==lo || hi-lo==1))
{
cout<<"You cheated. I quit!\n";
guess=true;
}
else
{
switch(answer)
{
case 1: //too low
lo=compGuess+1;
if((hi-lo+1)==0)
lo=compGuess;
compGuess=rand()%(hi-lo+1)+lo;
while(compGuess==lo)
{
compGuess=rand()%(hi-lo+1)+lo;
if(hi==lo)
break;
}
break;
case 2: //too hi
hi=compGuess-1;
if((hi-lo+1)==0)
hi=compGuess;
compGuess=rand()%(hi-lo+1)+lo;
while(compGuess==hi)
{
compGuess=rand()%(hi-lo+1)+lo;
if (hi==lo)
break;
}
break;
case 3: //correct
if(tries>1)
cout<<"I win! It only took me "<<tries<<" guesses!\n";
if (tries==1)
cout<<"I win! It only took me 1 guess!\n";
guess = true;
break;
}
}
}while(!guess);
cout<<"Type anything to exit!"<<endl;
cin>>nothing;
}