I'm writing a guessing game. The program picks a random number and says whether guesses are less than, greater than, or equal to it. All of that works, but I have two problems.
First, I want to be able to type q and quit the program, but when I type q, it goes through all of the turns as if I typed the same number. I don't really understand cin good enough to figure out what's going wrong, and I can't find my problem. I think I'm looking for the wrong things.
Second, the number that the program picks is always the same. I read about rand and srand, and how srand can change the numbers that rand gives, but I can't figure out how to make the number I give srand change without recompiling the program.
Here's my program.
Any other suggestions are welcome too.Code:#include <cstdlib> #include <iostream> using std::cout; class GuessingGame { private: int rightNumber; int turns; public: enum Result { LESS, EQUAL, GREATER }; GuessingGame(int low, int high) { rightNumber = (std::rand() % (high - low)) + low; turns = 0; } Result Guess(int guess) { ++turns; if (rightNumber < guess) { return LESS; } else if (rightNumber > guess) { return GREATER; } else { return EQUAL; } } int Turns() { return turns; } }; int main() { const int low = 0; const int high = 100; const int maxTurns = 10; GuessingGame game(low, high); do { int guess; GuessingGame::Result result; cout << "Pick a number between " << low << " and " << high << "\n"; std::cin >> guess; result = game.Guess(guess); if (result != GuessingGame::EQUAL) { int turnsLeft = maxTurns - game.Turns(); if (turnsLeft != 0) { if (result == GuessingGame::LESS) { cout << "The number is less than " << guess << "\n"; } else { cout << "The number is greater than " << guess << "\n"; } cout << "You have " << turnsLeft << " turns left\n"; } else { cout << "Game over. You have no more turns\n"; break; } } else { cout << "You won! The number was " << guess << "\n"; break; } } while (true); return 0; }Thanks!



LinkBack URL
About LinkBacks
Thanks! 




CornedBee
)