View Single Post
  #2 (permalink)  
Old July 12th, 2008, 12:20 AM
elvisfeverr elvisfeverr is offline
Authorized User
 
Join Date: Jan 2008
Posts: 24
Thanks: 0
Thanked 0 Times in 0 Posts
Default

i've found this working example you can investigate used functions to understand the code in detail.

#include <iostream>
using namespace std;

int main()
{
    int nAge;

    while (1)
    {
        cout << "Enter your age: ";
        cin >> nAge;

        if (cin.fail()) // no extraction took place
        {
            cin.clear(); // reset the state bits back to goodbit so we can use ignore()
            cin.ignore(1000, '\n'); // clear out the bad input from the stream
            continue; // try again
        }

        cin.ignore(1000, '\n'); // clear out any additional input from the stream
        if (cin.gcount() > 1) // if we cleared out more than one additional character
            continue; // we'll consider this input to be invalid

        if (nAge <= 0) // make sure nAge is positive
            continue;

    break;
    }

    cout << "You entered: " << nAge << endl;
    return 0;
}

Reply With Quote