Im currently working on an assignment and am trying to use try catch error handling for checking a user's input is a valid int.
I currently have this:
int inputValidation() {
int e = 0;
std::string es;
bool check = false;
do {
try {
if (!getline(std::cin, e)) {
throw stringInput;
}
else {
check = true;
}
}
catch (std::exception& er) {
std::cout << "Error! " << er.what() << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
} while (!check);
return e;
}
my issue is with the if ((getline(std::cin, e))){}
part. I've also tried using std::cin.getline(e, 256)
When calling the function I'm using this loop:
do {
std::cout << "Please select a month: ";
selectedMonth = inputValidation();
} while (selectedMonth < 1 || selectedMonth >(12 - actualMonth));
This simply makes sure they can only input a month from the current month until December.
I'm aware that I can use es
instead of e
, however that defeats the purpose of the error checking. My only idea coming off of this is to check on a conversion.
For whatever reason I seem to be getting the error "no instance of overloaded function "getline"" and am unsure of where I'm going wrong. If anyone could provide some insight I would be very grateful.
First Version
I managed to fix this by changing it to:
int inputValidation(std::string message) {
int e = NULL;
std::string es;
bool check = false;
do {
try {
std::cout << message;
getline(std::cin, es);
if (!atoi(es.c_str())) {
throw stringInput;
}
else {
e = atoi(es.c_str());
check = true;
}
}
catch (std::exception& er) {
std::cout << "Error! " << er.what() << std::endl;
}
} while (!check);
return e;
}
//In another function -->
do {
selectedMonth = inputValidation("Please select a month: ");
} while (selectedMonth < 1 || selectedMonth >(12 - actualMonth));
Working Version
As of the comments I changed this.
(The only difference is this version doesn't include an exception)
bool checkInput(int &input, std::string message) {
try {
std::cin >> input;
if (!std::cin.fail()) {
return true;
}
else {
throw(message);
}
}
catch (std::string e) {
std::cout << "Invalid input!" << std::endl;
std::cout << e << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return false;
}
}
//Elsewhere -->
std::cout << "Please input the lowest number you would like to check" << std::endl;
while (!checkInput(lowestNumber, "Please input the lowest number you would like to check"));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments