Hello pnwadike99,
Not enough code, but this can work.
I am guessing that "compGuess" is defined as an "int", but do not make people guess at this.
First you need to understand the difference between formatted and unformatted input.
Formatted input, as you are using,
cin >> userGuess;
detects the type of variable being used. If defined as an "int" it expects a number and a whole number at that to be entered. If you enter something that is not a whole number like a letter "cin" will fail and become unusable the rest of the program.
The opposite is unformatted input which will take everything up to and including the "\n". Usually used for strings.
When entering a number it is best to check the status of "cin" after input to make sure it worked.
This is untested, but I think it should work:
1 2 3 4 5 6 7 8 9 10 11 12
|
do
{
//user input
cout << "What is your guess? " << endl;
while(!(cin >> userGuess;))
{
std::cerr << "\n Invalid input! Try again.\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
}
| |
You can adjust the message as needed.
Line 6 does not need to be done after every formatted input, but is needed before an unformatted input using "std::getline".
Andy