>我目前正在处理作业,并尝试使用 try catch 错误处理来检查用户的输入是否有效。
我目前有这个:
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;
}
我的问题在于if ((getline(std::cin, e))){}
部分。我也尝试过使用std::cin.getline(e, 256)
调用函数时,我使用此循环:
do {
std::cout << "Please select a month: ";
selectedMonth = inputValidation();
} while (selectedMonth < 1 || selectedMonth >(12 - actualMonth));
这只是确保他们只能输入从当月到 12 月的一个月。
我知道我可以使用es
而不是e
,但这违背了错误检查的目的。我唯一的想法是检查转换。
无论出于何种原因,我似乎都收到错误"没有重载函数"getline"的实例",并且不确定我哪里出错了。如果有人能提供一些见解,我将不胜感激。
如果std::cin >> e
不合适,可以使用istringstream
:
std::string asText;
std::getline(cin,asText);
std::istringstream iss (asText);
if (iss >> e)
第一个版本
我设法通过将其更改为:
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));
工作版本
截至评论,我对此进行了更改。
(唯一的区别是此版本不包含例外(
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"));