Home > Article > Backend Development > How to Safely Convert a String to an Integer in C ?
Introduction:
In C , converting a string to an integer can be a straightforward task, but there are cases where we may encounter conversion failures. In such scenarios, it becomes necessary to handle these exceptions or failures gracefully.
Boost::lexical_cast:
Boost provides a versatile library with numerous utilities, including boost::lexical_cast. This function allows for the conversion of strings to various data types and throws an exception in case of failure. For instance:
<code class="cpp">#include <boost/lexical_cast.hpp> int i = boost::lexical_cast<int>(s);</code>
Without Boost:
If Boost is not available, we can utilize a C stream-based approach:
<code class="cpp">#include <sstream> int i; std::stringstream ss(s); if ((ss >> i).fail() || !(ss >> std::ws).eof()) { throw std::bad_cast(); }</code>
Faking Boost:
In the absence of Boost, it is possible to create a custom function that mimics its functionality:
<code class="cpp">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; }</code>
No-Throw Versions:
If desired, non-throw versions of these functions can be created by catching the appropriate exceptions and returning a boolean indicating success or failure:
<code class="cpp">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; } }</code>
The above is the detailed content of How to Safely Convert a String to an Integer in C ?. For more information, please follow other related articles on the PHP Chinese website!