0

Hi I wish that the following code can ask for an input of 2 integers within a certain range. If the condition is not satisfied, the loop kicks in until right numbers are typed in. The problem is that if I give a letter first (e.g. "r"), I will get an endless loop immediately (the system doesn't ask for the second but instead keeps showing "something wrong, please input again"). If the second input is a letter, the program can terminate. Could you tell me where goes wrong? Thanks very much.

#include <iostream>

int main()
{
int x, y;  
std::cout << "Please input 2 integers in the range: \n";
std::cin >> x >> y;

while (! ((x >= 0) && (x < 10) &&   
    (y >= 0) && (y < 10)) )
{
    std::cout << "\nsomething wrong, please input again\n";
    std::cin >> x >> y;
}
}
Ethan
  • 161
  • 2
  • 9
  • 1
    Have a look [here](https://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-ignore-after-reading-input) - you need to call `cin.clear();` and `std::cin.ignore(std::numeric_limits::max(), '\n');` to clear the error state out after it gets a bad input. – Tyler V May 29 '22 at 17:55
  • 1
    `int` can't read letters (exception: hex numbers, but that's not the case here) so if the first thing `>>` tries to interpret cannot be an `int` the stream sets a failure flag and refuses to read anything more until the failure is dealt with.. There are a lot of things that can go wrong with IO, so always check the stream state after every IO transaction to ensure the transaction succeeeded. – user4581301 May 29 '22 at 17:56
  • 1
    Note: `std::cin.ignore(std::numeric_limits::max(), '\n');` is usually the right thing to do, but sometimes you don't want to throw out everything. You'll find cases where if you fail to get a valid number, you'll want to read it as a string to see what you really got and maybe handle it differently or give the user a better error message. – user4581301 May 29 '22 at 17:58

0 Answers0