I've got a weird one here. strtol, atol and atoi all return an incorrect value when I pass in the following string:
long test = strtol("3087663490", &p, 10);
According to my debugger it returns 2147483647. I'm completely stumped on this. Any advice?
Your value is larger than what a signed long
type can represent. Try:
unsigned long test = strtoul("3087663490", &p, 10);
(You're getting 2147483647 since it is LONG_MAX
or 0x7FFFFFFF)
Correctly testing for errors from strtol()
is tricky. You need code similar to the below:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
int main()
{
char *n = "3087663490";
char *p;
long test;
errno = 0;
test = strtol(n, &p, 10);
if (p == n)
printf("No digits found.\n");
else if ((test == LONG_MIN || test == LONG_MAX) && errno == ERANGE)
printf("Value out of range.\n");
else
printf("Value is %ld\n", test);
return 0;
}
Running this shows what your problem is - Value out of range.
. Use a wider type, like long long
(and strtoll()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With