Recover From Input Stream Errors Input Stream Errors Input Errors
#include <iostream>
int main () {
std::cout << "i? ";
int i = 0;
std::cin >> i; // ← 1st
std::cout << "j? ";
int j = 0;
std::cin >> j; // ← 2nd
std::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
#include <iostream>
#include <limits>
void reset_cin () {
// clear all error status bits
std::cin.clear();
// clear input buffer
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
int main () {
std::cout << "i? ";
int i = 0;
std::cin >> i; // ← 1st
if (std::cin.fail()) reset_cin();
std::cout << "j? ";
int j = 0;
std::cin >> j; // ← 2nd
std::cout << "i: " << i <<", "
<< "j: " << j <<'\n';
}
Invalid Input for i
does not influence j
$ i? asdf
$ j? 3
i: 0, j: 3
Comments…