// cin_unget_char.cpp

#include <cassert>
#include <iostream>

using std::cin;
using std::cout;
using std::ios_base;

int get_value( char delimiter )
{
    int value = 0;
    while ( !( cin >> value ) ) {
        // cin is not good, more checks required.
        if ( cin.bad() ) {
            return 0; // signal error back to the operating system
        }
        if ( cin.eof() ) {
            return 0; // signal success to the operating system
        }
        if ( cin.fail() ) {
            cin.clear(); // go back to good state.
            // do something to recover...
            char ch = 0;
            if ( cin >> ch ) {
                if ( ch == delimiter ) {
                    // data delimiter was encountered and should be ignored:
                    continue;
                }
                // User typed something unexpected!
                cin.unget(); // put last character back into the input buffer
                cin.clear( ios_base::failbit  ); // restore cin.fail() state
                return ch; // report what the char they typed
            }
        }
    }
    return value;
}

int main()
{
    cout << "Please type some numbers separated by spaces or semicolons.\n";
    cout << "Type CTRL+Z followed by ENTER on windows (or CTRL+D on unix) to exit.\n";
    for (;;) {
        const char delimiter = ';';
        int value = get_value( delimiter );
        if ( !cin ) {
            // cin is not good, more checks required:
            if ( cin.bad() ) {
                cout << "cin is corrupted, exiting the program.\n";
                return 1; // signal error back to the operating system
            }
            if ( cin.eof() ) {
                cout << "EOF found, exiting the program.\n";
                return 0; // signal success to the operating system
            }
            if ( cin.fail() ) {
                cin.clear(); // go back to good state.
                char ch = 0;
                if ( cin >> ch ) {
                    assert( ch == value );
                    cout << "Sorry, character [" << ch << "] was unexpected at this time. Exiting...\n";
                    break;
                }
            }
        }
        cout << "You entered: " << value << '\n';
    }//for
    return 0;
}