• C

# strange strol() behaviour

anyone have any idea why this:

printf("%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n",
strtol("01", NULL, NULL),
strtol("02", NULL, NULL),
strtol("03", NULL, NULL),
strtol("04", NULL, NULL),
strtol("05", NULL, NULL),
strtol("06", NULL, NULL),
strtol("07", NULL, NULL),
strtol("08", NULL, NULL),
strtol("09", NULL, NULL),
strtol("10", NULL, NULL),
strtol("11", NULL, NULL),
strtol("12", NULL, NULL));

gives me this output:

1,2,3,4,5,6,7,0,0,10,11,12

??

thanks and regards.

LVL 37
###### Who is Participating?

Commented:
Your 'number base' (third parameter) seems to default to octal (base 8). Therefore, strtol stops parsing as it encounters a number outside of 0-7. Specify 10 as the third parameter to all strtol calls. This should fix the problem.
0

Author Commented:
thanks,

that is probably it, but i have worked around it like this:

int m = (month[0]-48)*10 + (month[1]-48);

still doesn't explain why it returns 0 for '09' as well, or why it returns correct values for '10', '11', '12'

regards.

0

Commented:
Yes, it explains your problem easily.

Octal (base-8) uses digits 0-7. Thus:

"00" becomes 0
"01" becomes 1
"02" becomes 2
"03" becomes 3
"04" becomes 4
"05" becomes 5
"06" becomes 6
"07" becomes 7
"08" becomes 0 because 8 is not recognized as a valid digit (0-7). Thus, strtol stops converting and keeps 0 as the result.
etc.

If you would have tried strtol("108", NULL, NULL) you probably would've ended up with 10 as a result.

Just use strtol("somevaluehere", NULL, 10) and it will work flawlessly.
0

Author Commented:

so it does make sense after all! ;-)

thanks indeed.

regards.
0

Commented:
No, the result of strtol("108", NULL, NULL) would be 108
strtol("0108", NULL, NULL) would be 8
strtol("012", NULL, NULL) would be 10
0

Commented:
ozo,

Well, it looks like meverest's runtime library behaves otherwise, from the results obtained.
0

Commented:
meverest's runtime library behaves exactly the way the standard requires strtol to behave
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.