//R. A. Hillyard
//cinTest2.cpp
//program to demonstrate how to recover from
//input errors using the cin member functions
//
//part two - now check for stream failure 
//if value read not valid - reset stream,
//read all remaining data on the line,
//and try again

#include<iostream>
#include<cctype>

using namespace std;

int main()
  {
  char charChoice;   //hold character entered by user
  int intChoice;     //hold int entered by user
  char next;         //hold next stream character

  do
    {
    cout << "\n*** Welcome to some program ***\n\n";
    
    bool flag = true;
    do
      {
      cout << "Enter an integer : ";
      cin >> intChoice;
      
      if(cin.fail())     //had a failure reading the input
        {
        cout << "Invalid input - try again\n";
        cin.clear();         //must reset stream after failure
        cin.get(next);       //now get any remaining chars from the stream
        while(next != '\n')  //reads until end of line
          cin.get(next);
        }
      else               //read stream ok
        {
        flag = false;    //exit loop if ok
        }
      }while(flag);
      
    cout << "You entered a: " << intChoice << endl;
    
    cout << "\nTry again?? [Y/N]: ";
    cin >> charChoice;
    charChoice = toupper(charChoice);
    }while(charChoice != 'N');
  }//end main
  
//run the program with the following data and note the results
//test1 - enter  5      (valid integer)
//test2 - enter  c      (char - invalid integer - catch it this time)
//test3 - enter  55.66  (what happened - still a problem???)