在编程中,经常需要将字符串转换为整数。虽然 C 为此目的提供了 std::atoi 函数,但它不能优雅地处理转换错误。为了解决这个问题,我们寻求一种允许错误处理的解决方案,类似于 C# 的 Int32.TryParse。
一种有效的方法是使用 Boost 库中的 lexical_cast 函数。它支持多种数据类型,并且如果转换失败可能会引发异常。这是一个示例:
#include
int main() {
std::string s;
std::cin >> s;
try {
int i = boost::lexical_cast(s);
// ...
} catch (...) {
// Handle error
}
}
如果 Boost 不可用,则可以使用 std::stringstream 和 >> 运算符的组合:
#include
#include
#include
int main() {
std::string s;
std::cin >> s;
try {
std::stringstream ss(s);
int i;
if ((ss >> i).fail() || !(ss >> std::ws).eof()) {
throw std::bad_cast();
}
// ...
} catch (...) {
// Handle error
}
}
作为最后的替代方案,可以创建 Boost 的 lexical_cast 函数的“假”版本:
#include
#include
#include
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;
}
int main() {
std::string s;
std::cin >> s;
try {
int i = lexical_cast(s);
// ...
} catch (...) {
// Handle error
}
}
如果需要无抛出版本,捕获适当的异常并返回指示成功或失败的布尔值:
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;
}
}
int main() {
std::string s;
std::cin >> s;
int i;
if (!lexical_cast(s, i)) {
std::cout
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3