I am trying to convert number stored in the c string to long int. But I am not getting the expected output:
char str[] = "987654321012345"; long int num ; num = 0; //num = atol(str); num = strtol(str, (char **) NULL, 10); printf("%ld", num);
Output : 821493369
gcc version 4.4.7 20120313 (Red Hat 4.4.7-16) Can you please advise what am I doing wrong here? Thanks.
Advertisement
Answer
In addition to using long long
, you can use exact width types from stdint.h
. For instance, to guarantee and 64-bit signed number you can use the int64_t
type. Regardless what you do, do not cast NULL
to char **
and always validate your conversions. E.g.,
#include <stdio.h> #include <stdlib.h> #include <errno.h> int main (void) { char str[] = "987654321012345"; long num = 0; errno = 0; num = strtol (str, NULL, 10); if (errno) { /* validate strtol conversion */ perror ("strtol conversion failed."); return 1; } printf ("%ldn", num); return 0; }
Example Use/Output
$ ./bin/strtoltst 987654321012345
There are additional error checks you can do on the conversion, but at minimum, make sure errno
is not set following your call to strtol
or strtoll
.
If you would like to use the guaranteed width types, then you can make the following changes:
... #include <stdint.h> ... int64_t num = 0; ... num = strtoll (str, NULL, 10);
The result is the same.