Checking int constraints in stoi () function in C ++

I have been given the string y, in which I am sure that it consists only of numbers. How to check if it exceeds the bounds of an integer before storing 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? 
+4
source share
3 answers

you can use the 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 error handling methods

+8
source

Catch the exception:

 string y = "2323298347293874928374927392374924" int x; try { x = stoi(y); } catch(...) { // String could not be read properly as an int. } 
+2
source

If there is a legitimate possibility that the string represents a value that is too large to be stored in int , convert it to something more and check if the result matches in int :

 long long temp = stoll(y); if (std::numeric_limits<int>::max() < temp || temp < std::numeric_limits<int>::min()) throw my_invalid_input_exception(); int i = temp; // "helpful" compilers will warn here; ignore them. 
0
source

Source: https://habr.com/ru/post/1499800/


All Articles