Question

I'm trying to convert a string of an arbitrary length to an int but so far it works only for strings of limited length. Code so far:

long long convertToInt (std::string x){
   long long number;
   std::istringstream ss(x);
   ss >> number;
   return number;}

for x=100000000000000000000000001 the function returns 0. Could someone explain why? Thanks.

Was it helpful?

Solution 2

The inbuilt integer types your compiler provides are only guaranteed to be capable of storing numbers of a specific magnitude. It looks like your number is larger than that. You may find the C++ program is reporting the error - try...

if (ss >> number)
    return number;
throw std::runtime_error("conversion of string to int failed");

...or whatever other error handling you feel like.

If you must use larger number, you could try double, or if that doesn't suit your needs then check out "arbitrary precision" libraries like GMP - you'll find lots of stackoverflow questions about handling large numbers with answers suggesting, contrasting and illustrating GMP and alternatives.

OTHER TIPS

The value "100000000000000000000000001" is to large to fit in a long long (or unsigned long long) so the extraction fails.

Use numeric_limits to determine the maximum value for types in your implementation:

#include <limits>

std::cout << std::numeric_limits<unsigned long long>::max() << "\n";
std::cout << std::numeric_limits<long long>::max() << "\n";
std::cout << "100000000000000000000000001\n";

prints:

18446744073709551615
9223372036854775807
100000000000000000000000001

Check the result of the extraction attempt to ensure extraction occurred:

if (ss >> number)
{
    return number;
}
// Report failure.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top