Checking the int limits in stoi() function in C++

Manmeet Saluja picture Manmeet Saluja · Aug 30, 2013 · Viewed 28.6k times · Source

I have been given a string y in which I'm ensured that it only consists digits. How do I check if it exceeds the bounds of an integer before storing it in an int variable using the stoi function?

string y = "2323298347293874928374927392374924"
int x = stoi(y); // The program gets aborted when I execute this as it exceeds the bounds
                 //   of int. How do I check the bounds before I store it?

Answer

4pie0 picture 4pie0 · Aug 30, 2013

you can use exception handling mechanism:

#include <stdexcept>

std::string y = "2323298347293874928374927392374924"
int x;

try {
  x = stoi(y);
}
catch(std::invalid_argument& e){
  // if no conversion could be performed
}
catch(std::out_of_range& e){
  // if the converted value would fall out of the range of the result type 
  // or if the underlying function (std::strtol or std::strtoull) sets errno 
  // to ERANGE.
}
catch(...) {
  // everything else
}

detailed description of stoi function and how to handle errors