Reputation: 51
I am currently trying to convert a string of length 18 which represents a long integer into a long integer so that I can then do a multiplication with the string. When I use stol to try to do the conversion, it runs into an out of range memory exception anytime the string length exceeds 10. It works fine when the string length is less than 10. Below is the relevant parts of my code:
for (unsigned int i = 0; i < numbers.size(); i++)
numbers[i] = numbers[i].substr(0, 10);
for (unsigned int i = 0; i < numbers.size(); i++)
n = stol(numbers[i].c_str());
Upvotes: 5
Views: 9421
Reputation: 157
This should depend on the implementation. For example, in GCC long
and int
are the same and on most machines are signed and 32 bits. This means that the largest number you can put there is 2147483647, that is, having 10 digits.
You should probably use stoll
as its return type is long long
-- 64 bits.
Upvotes: 7
Reputation: 45674
Are you sure long
is more than 32 bits on your implementation, in particular can represent that number?
While the standard does not mandate the exact range of the type, it only guarantees numbers in the range +/- 2147483647 will fit.
Anything more is at the discretion of the implementation.
Upvotes: 4
Reputation: 799082
A long
only supports values between -2147483648 and 2147483647 inclusive. If you want to try using a long long
instead then you'll need to use stoll()
.
Upvotes: 4