You should test std::cin.fail()
after the while
loop because if std::cin >> number
fails, the body of the while
loop will not be entered.
You could also restructure the tests a bit to not have to perform the same tests over and over again. Also, std::endl
flushes the output stream which is unnecessary in the vast majority of cases and just takes extra time.
// ...
while (std::cin >> number)
{
if (number < 0 || number > 99)
{
std::cout << "[WARNING] : Number must be between 0 and 99
";
}
else if (number < random) // no need to test if it's out of bounds
{
std::cout << "This number is larger.
";
}
else if (number > random) // no need to test if it's out of bounds
{
std::cout << "This number is smaller.
";
}
else // no need to test anything
{
std::cout << "Great! You're right!
";
break;
}
}
if(std::cin.fail())
{
std::cout << "Error encountered, exiting...
";
return 1;
}
return 0;
}
The difference between std::cout
and std::cerr
is which output stream it'll use. People running your program can read both streams separately if they want to do logging of errors for example.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…