5

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());
2
  • Are you sure long int is more than 32 bits on your implementation? Commented Feb 20, 2015 at 2:07
  • 1
    That appears to be the problem. I tried just assigning the value to n manually and it didn't work correctly. I switched to a long long int and it worked. Thanks. Commented Feb 20, 2015 at 2:11

3 Answers 3

7

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.

4

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().

1
  • No, the lower limit can be -2147483647. And then that would be the minimal range. Commented Feb 20, 2015 at 2:09
4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.