Advertisement
Guest User

Untitled

a guest
May 17th, 2014
346
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. #include <iostream>
  2. #include <sstream>
  3. #include <ctime>
  4. #include <cstdlib>
  5.  
  6. using namespace std;
  7.  
  8. int main (int argc, char** argv)
  9. {
  10.     // the upper and lower limits of which numbers we can choose from.
  11.     int numLower = 1;
  12.     int numHigher = 10;
  13.     // generate our random number
  14.     srand(time(NULL));
  15.     int secret = rand() % numHigher + numLower;
  16.     // the variables we will use to hold our answer, split among three.
  17.     stringstream answerBuffer;
  18.     int answerNumber;
  19.     string answerString;
  20.     // useless statistical knickknacks
  21.     int winCount = 0;
  22.     int tryCount = 0;
  23.     // flags whether we are still playing the game or not.
  24.     bool playing = true;
  25.  
  26.     do
  27.     {
  28.         cout << "Guess a number between 1 and 10, enter q to quit." << endl;
  29.         // get our input from cin
  30.         getline(cin, answerString);
  31.         if (answerString.compare("q") == 0 || answerString.compare("Q") == 0)
  32.         {
  33.             // if Q is found, skip the game and end the loop.
  34.             playing = false;
  35.         }
  36.         else
  37.         {
  38.             // otherwise, play a round.
  39.             tryCount++;
  40.             // insert our answer into the stringstream buffer
  41.             answerBuffer << answerString;
  42.             // extract our answer into the answerNumber integer
  43.             answerBuffer >> answerNumber;
  44.             if (answerNumber == secret)
  45.             {
  46.                 cout << "You picked the right number!" << endl;
  47.                 // generate a new number so we can play again
  48.                 secret = rand() % numHigher + numLower;
  49.                 winCount++;
  50.             }
  51.             else if (answerNumber > numHigher || answerNumber < numLower)
  52.                 cout << "You picked an out of bounds number!" << endl;
  53.             else
  54.                 cout << "You picked the wrong number." << endl;
  55.             //clear the stringstream so we can use it again.
  56.             answerBuffer.clear();
  57.         }
  58.     } while (playing);
  59.     cout << "Goodbye! You guessed the right number " << winCount << " times out of " << tryCount << " attempts." << endl;
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement