Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Number guessing game with cheat detection
- #include <iostream>
- #include <string>
- #include <time.h>
- using namespace std; //Allows the use of std:: namespace without prefix
- //Work out new guess
- int Guess(int tLow, int tHigh)
- {
- return tLow + (tHigh - tLow) / 2; //Find number mid-way in range
- }
- //Guess a number vFrom must be lower than vTo
- int IguessYourNumber(int vFrom, int vTo)
- {
- cout << "Think of a number between " << vFrom << " and " << vTo << endl; //User prompt
- int tCount = 1;
- for (;;) //Infinite loop unless we break
- {
- int tGuess = Guess(vFrom, vTo);
- cout << "Debug Info vFrom=" << vFrom << " vTo=" << vTo << endl; //Debug info
- cout << "My guess is (" << tGuess << ") please choose c=correct,l=lower,h=higher?"; //User prompt
- string tInput; //Space for input string
- cin >> tInput;
- if (tInput == "l")
- {
- vTo = tGuess - 1; //Range must be lower than guess
- tCount++; //Up Guess count
- }
- else if (tInput == "h")
- {
- vFrom = tGuess + 1; //Range must be higher than guess
- tCount++;
- }
- else if (tInput == "c") //Number is correct
- {
- cout << "It took me just " << tCount << " Guesses" << endl; //Brag
- break;
- }
- else //Invalid use pption
- {
- cout << "Valid options are c,l or h" << endl;
- }
- if (!(vFrom <= vTo)) //If Low tries to go above high we have a cheater!
- {
- cout << "You are cheating" << endl;
- tCount = -1; //Cheater
- break;
- }
- }
- return tCount; //Return number of guesses or -1 for a cheater
- }
- int main()
- {
- IguessYourNumber(1, 100);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement