使用 C 中的错误处理将字符串转换为 int
将字符串转换为整数是编程中的常见任务。但是,在某些情况下,字符串值可能无法成功转换为整数。在这种情况下,优雅地处理转换失败至关重要。
boost::lexical_cast
将字符串转换为 int 时出现错误的最直接方法之一处理方法是使用 boost::lexical_cast 函数。如果转换无法继续,该函数会抛出异常,从而允许我们捕获它并做出适当的响应。
#include
int main() {
std::string s;
std::cin >> s;
try {
int i = boost::lexical_cast(s);
} catch (...) {
// Handle the conversion failure
}
}
使用标准库函数
不使用 boost 的另一种方法是利用标准库函数,例如 std::stringstream 和 std::bad_cast。
#include
#include
int main() {
std::string s;
std::cin >> s;
std::stringstream ss(s);
int i;
if ((ss >> i).fail() || !(ss >> std::ws).eof()) {
throw std::bad_cast();
}
}
自定义函数
为了实现可定制性,您可以创建一个模拟 boost::lexical_cast 功能并管理转换失败的函数。
template
T lexical_cast(const std::string& s) {
std::stringstream ss(s);
T result;
if ((ss >> result).fail() || !(ss >> std::ws).eof()) {
throw std::bad_cast();
}
return result;
}
非抛出版本
如果您希望避免抛出异常,您可以通过捕获异常并返回失败来创建上述函数的无抛出版本Indicator.
template
bool lexical_cast(const std::string& s, T& t) {
try {
t = lexical_cast(s);
return true;
} catch (const std::bad_cast& e) {
return false;
}
}
使用这些方法,您可以高效地将字符串转换为整数,同时处理潜在的转换失败。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3