Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 554
Manmeet Saluja Avatar asked Aug 30 '13 13:08

Manmeet Saluja


People also ask

What is stoi function in C?

The stoi() function accepts a string as an argument and converts the string's integer component to an integer type.

What is the time complexity of stoi?

what is time complexity of above mentioned stoi function? Theoretically it is O(n) where n is the length of the string. However since integers are bounded in size (a 32-bit integer can be represented with at most 11 chars in base10 form) it is actually O(1). A 32-bit integer is in range -2147483648 to 2147483647.

What does stoi return?

In C++, the stoi() function converts a string to an integer value. The function is shorthand for “string to integer,” and C++ programmers use it to parse integers out of strings.

What is the difference between stoi and Atoi?

First, atoi() converts C strings (null-terminated character arrays) to an integer, while stoi() converts the C++ string to an integer. Second, the atoi() function will silently fail if the string is not convertible to an int , while the stoi() function will simply throw an exception.


2 Answers

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

like image 140
4pie0 Avatar answered Sep 22 '22 14:09

4pie0


Catch the exception:

string y = "2323298347293874928374927392374924"
int x;

try {
  x = stoi(y);
}
catch(...) {
  // String could not be read properly as an int.
}
like image 24
Sani Singh Huttunen Avatar answered Sep 18 '22 14:09

Sani Singh Huttunen