Author | Post | |||
kryptos |
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! |
|||
07.07.2005 12:37:26 |
|
|||
Phas(retired) |
Quote: 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; |
|||
07.07.2005 13:08:15 |
|
|||
sebasjm |
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! |
|||
07.07.2005 13:15:32 |
|
|||
kryptos |
Thanks for the explaination and solution! |
|||
07.07.2005 14:55:36 |
|