I'm trying to write a code for input a int data in a security way. If the user enter with a letter, an error message could be showed.
My code is the following:
#include <iostream>
using namespace std;
int main(){
int a;
do {
cout << "Enter the value of a: ";
cin >> a;
if (cin.fail()){
cout << "You put an invalid value, try again" << endl;
cin.ignore(); //I've already tried cin.clear();
}
}while(cin.fail());
return 0;
}
When I run my code and enter with a letter, the program execute in an infinite loop. I'll be happy, if somebody can help me.