Reputation: 1
I'm doing some homework and trying to make it safe from character input but somehow writing a character inside still breaks it because it makes the loop infinite. Can anyone suggest a way to fix it? Here's the code:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
srand( time( NULL ) );
int given = 0;
int imaginarynum = ( std::rand() % 99 ) + 1;
int tries = 0;
std::cout << "Hello! We'regoing to play an easy game! I'm goinng to think of a number between 1-100 and you'll have to guess it! " << std::endl;
std::cout << given << " "<< imaginarynum;
while(given < imaginarynum || given > imaginarynum)
{
std::cin >> given;
bool error = std::cin.fail();
std::cin.clear();
std::cin.sync();
while(error != false)
{
std::cout << "That's not a number!" << std::endl;
std::cin >> given;
bool error = std::cin.fail();
std::cin.clear();
}
if (given < imaginarynum)
{
std::cout << "I thought of a bigger number! " << std::endl;
std::cout << "Guess again!" << std::endl;
tries = tries + 1;
}else if (given > imaginarynum)
{
std::cout << "I thought of a smaller number! " << std::endl;
std::cout << "Guess again!" << std::endl;
tries = tries + 1;
}
else
{`enter code here`
tries = tries + 1;
std::cout << "Good job! " << std::endl << "It took you: " << tries << " Tries!";
}
}
return 0;
}
Upvotes: 0
Views: 112
Reputation: 311068
The problem is that you are using two variables error
while(error != false)
{
std::cout << "That's not a number!" << std::endl;
std::cin >> given;
bool error = std::cin.fail();
std::cin.clear();
}
Within the loop you declared a new variable. Substitute the declaration for an assignment statement
while(error != false)
{
std::cout << "That's not a number!" << std::endl;
std::cin >> given;
error = std::cin.fail();
std::cin.clear();
}
And the second problem is that you need to clear the buffer. For example
#include <limits>
//...
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
The loop will look the following way
#include <limits>
//...
while(error != false)
{
std::cout << "That's not a number!" << std::endl;
std::cin >> given;
error = std::cin.fail();
std::cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}
Upvotes: 5