In programming, it's often necessary to convert strings to integers. While C provides the std::atoi function for this purpose, it doesn't handle conversion errors gracefully. To address this, we seek a solution that allows for error handling, similar to C#'s Int32.TryParse.
An efficient approach is to use the lexical_cast function from the Boost library. It supports a variety of data types and can throw an exception if the cast fails. Here's an example:
#include
int main() {
std::string s;
std::cin >> s;
try {
int i = boost::lexical_cast(s);
// ...
} catch (...) {
// Handle error
}
}
If Boost is not available, a combination of std::stringstream and >> operator can be used:
#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
}
}
As a final alternative, a "fake" version of Boost's lexical_cast function can be created:
#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
}
}
If a no-throw version is desired, catch the appropriate exceptions and return a boolean indicating success or failure:
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
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3