+ 1

How to validate user input as an integer when using cin

I am working error handling and validation of a code write now. I have searched Sololearn and other places like StackOverflow and found some stuff, but nothing that has worked yet. If there is something out there that I wasn't able to find that answers my question, please feel free to post the link! Here is some code I was using to test a function that receives and validate user input (I was testing it just using the "Menu" option so far). The context of the function is a plinko simulator. Here is the test code: #include <iostream> #include <climits> using namespace std; const int MENU_OPTION = 4; int GetInputNumber(string inputUse, int lowerBound = INT_MIN, int upperBound = INT_MAX) { int inputNumber = 0; do { if (inputUse == "Menu") { cout << "Enter your selection now: "; cin >> inputNumber; cout << inputNumber << endl; if (!(inputNumber >= lowerBound && inputNumber <= upperBound)) { cout << "Invalid selection. Enter " << MENU_OPTION << " to see options." << endl; cout << endl; cin.clear(); cin.ignore(1000, '\n'); } } else if (inputUse == "Choose Slot") { cout << "Which slot do you want to drop the chip in (0-8)? "; cin >> inputNumber; cout << inputNumber << endl; if (!(inputNumber >= lowerBound && inputNumber <= upperBound)) { cout << "Invalid slot." << endl; cout << endl; } } else if (inputUse == "Chip Amount") { cout << "How many chips do you want to drop (>0)? "; cin >> inputNumber; cout << inputNumber << endl; if (!(inputNumber >= lowerBound && inputNumber <= upperBound)) { cout << "Invalid number of chips." << endl; cout << endl; } } else { cout << "GetInputNumber Error" << endl; break; } if (!(cin >> inputNumber)) { cout << "That was not an integer" << endl; inputNumber = 1; //cin.clear(); //cin.ignore(1000, '\n'); } } while (!(inputNumber >= lowerBound && inputNumber <= upperBound)); return inputNumber; } //int main()

25th Jul 2018, 1:45 AM
Parker king
Parker king - avatar
4 Antworten
+ 4
do { std::cin.clear(); std::cin.ignore(512, '\n'); std::cin >> InputNumber; } while (std::cin.fail());
25th Jul 2018, 2:02 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Or better, try-catch blocks. while (loop) { try { std::cin >> InputNumber; if (std::cin.fail()) throw 0; if (inputOutOfBound) throw 1; //... etc // if no errors thrown, loop = false; // exit loop } catch (int err) { std::cin.clear(); std::cin.ignore(512, '\n'); switch (err) { // error messages here } } }
25th Jul 2018, 2:07 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
int main() { GetInputNumber("Menu"); return 0; }
25th Jul 2018, 1:48 AM
Parker king
Parker king - avatar
+ 1
Hatsy Rei the missing puzzle piece was cin.fail(). Thanks!
25th Jul 2018, 6:37 AM
Parker king
Parker king - avatar