Checking the int limits in stoi() function in C++ [duplicate]
Asked Answered
S

3

14

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?
Scintillate answered 30/8, 2013 at 13:24 Comment(3)
why not catch the exception and handle it accordingly?Fidellia
You might want to read a reference such as this about what happens when there is a problem parsing the string.Jeer
Thanks a lot guys! Yup I will go through the reference!Scintillate
S
22

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

Shumaker answered 30/8, 2013 at 13:28 Comment(0)
K
3

Catch the exception:

string y = "2323298347293874928374927392374924"
int x;

try {
  x = stoi(y);
}
catch(...) {
  // String could not be read properly as an int.
}
Kutz answered 30/8, 2013 at 13:28 Comment(0)
L
1

If there is a legitimate possibility that the string represents a value that's too large to store in an int, convert it to something larger and check whether the result fits in an 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.
Lazor answered 30/8, 2013 at 13:45 Comment(4)
What if it doesn't fit into long long?Crandell
If it doesn't fit into long long it's not a valid integral value (ignoring extended integral types), and you get an exception.Lazor
You may as well try to convert directly to int or the desired type.Crandell
@NeilKirk - no, that doesn't meet the original requirements, which was detecting whether it fits into an int. But I've changed the behavior on out of range to make that clearer.Lazor

© 2022 - 2024 — McMap. All rights reserved.