Beginner's Guide
    First Steps
    Input & Output
    Custom Types – Part 1
    Diagnostics
    Standard Library – Part 1
    Function Objects
    Standard Library – Part 2
    Code Organization
    Custom Types – Part 2
    Generic Programming
    Memory Management
    Software Design Basics

    Recover From Input Stream Errors Input Stream Errors Input Errors

    What's The Problem? Problem

    Example: Successive Inputs Example

    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