• 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
meverestAsked:
Who is Participating?
 
bbousquetConnect With a Mentor 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
 
meverestAuthor 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'

but thanks for your response.

regards.


0
 
bbousquetCommented:
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
Protect Your Employees from Wi-Fi Threats

As Wi-Fi growth and popularity continues to climb, not everyone understands the risks that come with connecting to public Wi-Fi or even offering Wi-Fi to employees, visitors and guests. Download the resource kit to make sure your safe wherever business takes you!

 
meverestAuthor Commented:
well how about that?

so it does make sense after all! ;-)

thanks indeed.

regards.
0
 
ozoCommented:
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
 
bbousquetCommented:
ozo,

Well, it looks like meverest's runtime library behaves otherwise, from the results obtained.
0
 
ozoCommented:
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.

All Courses

From novice to tech pro — start learning today.