Home >Backend Development >C++ >How to Convert Strings to Integers with Error Handling in C ?
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:
<code class="cpp">#include <boost/lexical_cast.hpp> int main() { std::string s; std::cin >> s; try { int i = boost::lexical_cast<int>(s); // ... } catch (...) { // Handle error } }</code>
If Boost is not available, a combination of std::stringstream and >> operator can be used:
<code class="cpp">#include <iostream> #include <sstream> #include <string> 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 } }</code>
As a final alternative, a "fake" version of Boost's lexical_cast function can be created:
<code class="cpp">#include <iostream> #include <sstream> #include <string> template <typename T> 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<int>(s); // ... } catch (...) { // Handle error } }</code>
If a no-throw version is desired, catch the appropriate exceptions and return a boolean indicating success or failure:
<code class="cpp">template <typename T> bool lexical_cast(const std::string& s, T& t) { try { t = lexical_cast<T>(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 << "Bad cast." << std::endl; } }</code>
The above is the detailed content of How to Convert Strings to Integers with Error Handling in C ?. For more information, please follow other related articles on the PHP Chinese website!