Topic: "programming problem" (page 1 of 1)

1
Author Post
kryptos
groupmastergroupmastergroupmastergroupmaster
Hi,

Im not sure why my program gives screwed up results when i use the following line of code:
sum += atoi(&isbn[10-i]) * i;

However it gives the results i want when i use this line of code instead:
temp[0] = isbn[10-i];
sum += atoi(temp) * i;

where both temp and isbn are character arrays. Can some please tell me why does this happen.

Thanks!
private message
Phas(retired)
groupmastergroupmastergroupmastergroupmastergroupmastergroupmastergroupmastergroupmastergroupmastergroupmastergroupmastergroupmastergroupmaster
QuoteQuote:
Im not sure why my program gives screwed up results when i use the following line of code:
sum += atoi(&isbn[10-i]) * i;

However it gives the results i want when i use this line of code instead:
temp[0] = isbn[10-i];
sum += atoi(temp) * i;

where both temp and isbn are character arrays. Can some please tell me why does this happen.

Probably temp[1] == 0 but isbn[10-i+1] != 0. If you want to convert just one char (I bet form '0' to '9') to a number just do the following:
sum += (int)(isbn[10-i]-'0') * i;

private message EMail Website
sebasjm
groupmastergroupmastergroupmastergroupmaster
Hi!

Is because atoi() is waiting for a String ( char* ) and a String must finish with a null character.
Here:
sum += atoi(&isbn[10-i]) * i;
What it will do, depending on what are you doing with "i", lets say that it's in a FOR loop from 1 to 10 and isbn is "1234567890"
sum will be:
sum += atoi("0")*i;
then
sum += aoti("90")*i;
sum += aoti("890")*i;
ann so....
but if you use
temp[0] = isbn[10-i];
maybe temp[1] has a null character it will sum like you want. That is, if what you want is sum the numbers of the isbn ;)

I hope i could have help you ;)

SebaS!
private message EMail
kryptos
groupmastergroupmastergroupmastergroupmaster
Thanks for the explaination and solution!
private message

Topic: "programming problem" (page 1 of 1)

1