Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. //Number guessing game with cheat detection
  2.  
  3.  
  4. #include <iostream>
  5. #include <string>
  6. #include <time.h>
  7.  
  8. using namespace std; //Allows the use of std:: namespace without prefix
  9.  
  10. //Work out new guess
  11. int Guess(int tLow, int tHigh)
  12. {
  13. return tLow + (tHigh - tLow) / 2; //Find number mid-way in range
  14. }
  15.  
  16. //Guess a number vFrom must be lower than vTo
  17. int IguessYourNumber(int vFrom, int vTo)
  18. {
  19. cout << "Think of a number between " << vFrom << " and " << vTo << endl; //User prompt
  20.  
  21. int tCount = 1;
  22. for (;;) //Infinite loop unless we break
  23. {
  24. int tGuess = Guess(vFrom, vTo);
  25. cout << "Debug Info vFrom=" << vFrom << " vTo=" << vTo << endl; //Debug info
  26. cout << "My guess is (" << tGuess << ") please choose c=correct,l=lower,h=higher?"; //User prompt
  27. string tInput; //Space for input string
  28. cin >> tInput;
  29. if (tInput == "l")
  30. {
  31. vTo = tGuess - 1; //Range must be lower than guess
  32. tCount++; //Up Guess count
  33. }
  34. else if (tInput == "h")
  35. {
  36. vFrom = tGuess + 1; //Range must be higher than guess
  37. tCount++;
  38. }
  39. else if (tInput == "c") //Number is correct
  40. {
  41. cout << "It took me just " << tCount << " Guesses" << endl; //Brag
  42. break;
  43. }
  44. else //Invalid use pption
  45. {
  46. cout << "Valid options are c,l or h" << endl;
  47. }
  48. if (!(vFrom <= vTo)) //If Low tries to go above high we have a cheater!
  49. {
  50. cout << "You are cheating" << endl;
  51. tCount = -1; //Cheater
  52. break;
  53. }
  54. }
  55. return tCount; //Return number of guesses or -1 for a cheater
  56. }
  57.  
  58. int main()
  59. {
  60. IguessYourNumber(1, 100);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement