Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ stol throwing out of range exception for string length 10 or longer

Tags:

c++

string

c++11

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());
like image 504
Drue Gockel Avatar asked Dec 08 '22 04:12

Drue Gockel


1 Answers

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.

like image 152
r0fg1 Avatar answered Apr 27 '23 00:04

r0fg1