Beginner's Guide
    First Steps
    Input & Output
    Basic Custom Types
    Diagnostics
    Standard Library
    Code Organization
    Powerful Custom Types
    Generic Programming
    Memory Management
    Software Design Basics

    Recover From Input Stream ErrorsInput Stream ErrorsInput Errors

    Example: Successive Inputs Example

    What's The Problem? Explanation

    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 set
    • cin's buffer content is not discarded and still contains the problematic input
    • any following attempt to read an int from cin 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