Convert stdin string input to an integer using cin

#include <iostream>
#include <limits>
 
using namespace std;
 
int main ()
{
    int i;
    cout << "Enter an integer: ";
    cout.flush();
    while ( (cin >> i).fail() )
    {
        // Clear the error flag in the cin object
        cin.clear();
        // Discard the erroneous user input
        cin.ignore(numeric_limits<streamsize>::max(), 'n');
        cout << "Please try again: ";
        cout.flush();
    }
    cout << "The integer value is: " << i;
}