Home > Backend Development > C++ > body text

How to Safely Convert a String to an Integer in C ?

Susan Sarandon
Release: 2024-11-05 14:23:02
Original
973 people have browsed it

How to Safely Convert a String to an Integer in C  ?

Convert String to Int with Bool/Fail 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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!