I am trying to run a while loop that has a range between 0 and 6 but if you input a character the while loop exits and the program goes into a fail state. I am looking for some help on how to combine the while loop with the range and the while loop that clears the fail state...If that makes any sense...
Doing numeric input with error handling in C++ is notoriously tricky. These are 2 general functions that will help. The first obtains an int value and deals with non-int input. The second uses the first to obtain a valid int within a specified range. Neither will return until a valid input is provided.
Hi there, thank you for your response. The problem here is that i need to use the basic topics covered in our course and i am unfamiliar with some of the syntax used in these functions.
#include <string>
#include <limits>
#include <iostream>
int getInp(const std::string& prm) {
int n {};
while ((std::cout << prm) && !(std::cin >> n)) {
std::cout << "Invalid input. Not an int\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return n;
}
int getInp(const std::string& prm, int low, int upper) {
int num {};
do {
num = getInp(prm);
} while ((num < low || num > upper) && (std::cout << "Input not in range\n"));
return num;
}
int main() {
constauto percent { getInp("Enter percentage of salary contributed to pension (0-6 percent): ", 0, 6) };
std::cout << percent << '\n';
}
To be even simpler,
std::numeric_limits<std::streamsize>::max()
could be replaced with a large constant - say 1000.