Recover From Input Stream Errors Input Stream Errors Input Errors
int main() {
cout << "i? ";
int i = 0;
cin >> i; // ← 1st
cout << "j? ";
int j = 0;
cin >> j; // ← 2nd
cout << "i: " << i <<", "
<< "j: " << j <<'\n';
}
Valid input ⇒ expected behavior
$ i? 2
$ j? 3
i: 2, j: 3
Invalid input for i
⇒
j
not read!
$ i? asdf
i: 0, j: 0
Why Does This Happen?
If cin
in the following code fragment
int i = 0;
cin >> i;
reads characters that cannot be converted to an int
:
cin
's failbit is setcin
's buffer content is not discarded and still contains the problematic input- any following attempt to read an
int
fromcin
will also fail
Solution: Reset Input Stream After Error Solution: Reset Stream Solution
- clear
cin
's failbit - clear
cin
's input buffer
void reset_cin() {
// clear all error status bits
cin.clear();
// clear input buffer
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
int main() {
cout << "i? ";
int i = 0;
cin >> i; // ← 1st
if(cin.fail()) reset_cin();
cout << "j? ";
int j = 0;
cin >> j; // ← 2nd
cout << "i: " << i <<", "
<< "j: " << j <<'\n';
}
Invalid Input for i
does not influence j
$ i? asdf
$ j? 3
i: 0, j: 3
Comments