Reputation: 67
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.
Upvotes: 1
Views: 167
Reputation: 121971
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.
Upvotes: 5
Reputation: 106126
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.
Upvotes: 1