[英]How do I validate int input using std::stoi() in C++?
有没有办法检查字符串输入是否可以在 C++ 中使用std::stoi()
转换为 int? (例如,我可以检查是否会抛出 invalid_argument 异常?)
一个不起作用的例子,但希望能解释我正在尝试做的事情:
string response;
cout << prompt;
if (std::stoi(response) throws invalid_argument) { //Something like this
return std::stoi(response);
}
else {
badInput = true;
cout << "Invalid input. Please try again!\n";
}
研究:
我找到了几种检查字符串是否为 int 的方法,但我希望有一种方法可以使用std::stoi()
来做到这一点,但我还没有找到。
您应该在抛出异常时捕获异常,而不是试图预先确定是否会抛出异常。
string response;
cin >> response;
try {
return std::stoi(response);
}
catch (...) {
badInput = true;
cout << "Invalid input. Please try again!\n";
}
如果无法执行转换,则std::stoi()
抛出异常。 查看此 c++ 文档中的“异常”部分http://www.cplusplus.com/reference/string/stoi/
std::stoi 尽可能多地转换,只有在没有任何转换的情况下才会抛出异常。 但是,std::stoi 接受一个表示开始索引的指针参数,该参数被更新为终止转换的字符。 在此处查看 MSDN stoi 文档。
您可以使用 stoi 进行测试,传递 0 作为起始索引,然后验证返回的索引是否与字符串的总长度相同。
将以下内容视为伪代码,它应该让您了解如何使其工作,假设响应是 std::string:
std::size_t index = 0;
auto result = std::stoi(response, &index);
if(index == response.length()){
// successful conversion
return result;
}
else{
// something in the string stopped the conversion, at index
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.