当将 getline 与 int 一起使用时,如何修复"没有重载函数 'getline' 的实例与参数列表匹配"
How to fix "no instance of overloaded function "getline" matches the argument list" when using getline with an int
>我目前正在处理作业,并尝试使用 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"));
相关文章:
- getline 函数似乎在 C++ 中不起作用
- 如何以及何时使用 getline 函数执行计算?
- 对c++中的输入使用getline函数时忽略第一个字符
- 使用 c++ 中的 getline 函数连续读取两行
- 此C Getline函数的C 代码有什么问题
- 使用 getline 函数读取文件,但第一列显示为空
- 使用 getline 函数获取分段错误
- getline函数只读取第一行
- c++getline函数不允许我输入
- 使用getline函数时出现问题
- 如何正确使用标准::getline函数
- C++:将带有空格的cin转换为不带getline函数的字符串
- 而循环构造与 getline 函数相结合,一直持续到 EOF
- 使用 getline 函数的最优雅方式
- 使用 getline 函数解析 C++ 中的字符串
- 我们如何在程序中同时使用 cin 和 getline 函数
- std::getline函数(fstream _Lock())出错
- 验证输入和getline()函数
- **编译器错误** - getline() 函数不接受第一个参数"std:ifstream"是什么我的问题?
- c++中的Getline()函数需要少一个输入