I’ve got the following piece of code:
...
int x = 0;
int y = 0;
cin >> x >> y;
if (x == -1 && y == -1) {
cout << "exit!";
}
else {
doSomething();
}
...
And it works, but only if I enter 2 numbers. If I were to enter a letter, like ‘n’, the program gets thrown into an infinite loop. How do I check to make sure the user entered a number and avoid the infinite loop?
Once
cinsees a type disagreement between the input data and the variables you’re trying to read into, it enters a “fail” state. The conflicting variables won’t be updated. Observe:There are two ways to avoid the problem you’re seeing.
cin.good()instead of comparing the numbers to-1.cinto behave more robustly, read intostrings instead ofints, and manually verify that they contain only numeric characters. You can then usestringstreamto easily convert the strings to numbers.