"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I handle conversion errors when converting a string to an integer in C++?

How can I handle conversion errors when converting a string to an integer in C++?

Published on 2024-11-15
Browse:605

How can I handle conversion errors when converting a string to an integer in C  ?

Convert String to int with Error Handling in C

Converting a string to an integer is a common task in programming. However, there may be instances where the string value cannot be successfully converted to an integer. In such scenarios, it's crucial to handle the conversion failure gracefully.

boost::lexical_cast

One of the most straightforward methods for converting a string to an int with error handling is to use the boost::lexical_cast function. This function throws an exception if the conversion cannot proceed, allowing us to catch it and respond appropriately.

#include 

int main() {
  std::string s;
  std::cin >> s;

  try {
    int i = boost::lexical_cast(s);
  } catch (...) {
    // Handle the conversion failure
  }
}

Using Standard Library Functions

An alternative approach without using boost is to utilize the standard library functions such as std::stringstream and std::bad_cast.

#include 
#include 

int main() {
  std::string s;
  std::cin >> s;

  std::stringstream ss(s);
  int i;

  if ((ss >> i).fail() || !(ss >> std::ws).eof()) {
    throw std::bad_cast();
  }
}

Custom Function

For customizability, you can create a function that emulates the functionality of boost::lexical_cast and manages the conversion failures.

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;
}

Non-Throwing Versions

If you prefer to avoid throwing exceptions, you can create no-throw versions of the above functions by catching the exceptions and returning a failure indicator.

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;
  }
}

Using these methods, you can efficiently convert strings to integers while handling potential conversion failures.

Latest tutorial More>

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