I am trying to validate an integer entered by the user (getUserInteger). When the value of the input is not an integer, the while loop is supposed to clear the buffer, reset the error status of the buffer, print "bad entry, try again: " and then ask for a new number.
It looks like everything is working well up until a new number is asked for. "cin >> number" whithin the loop never seams 'hit' and continues iterating through the loop and cout'ing "bad entry...". I cannot for the life of me figure out why. Thanks for the help!
#include <iostream>
#include <string>
#include <limits>
using namespace std;
// ----- Prototypes -----
int getUserInteger();
// ----- Main -----
int main (){
int userNumber;
userNumber = getUserInteger();
}
// ----- Functions -----
int getUserInteger() {
int number;
cin >> number;
while ( cin.fail() ) { // read failed, not int?
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //clear buffer through 'enter'
cin.clear(); // reset error buffer
cout << "bad entry, try again: " << endl;
cin >> number;
}
return number;
}
cin.ignore
should come after cin.clear
.
Wrong:
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //clear buffer through 'enter'
cin.clear(); // reset error buffer
Fixed:
cin.clear(); // reset error buffer
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //clear buffer through 'enter'