|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
getchar() and array
Hi,
Can anyone tell me why I have to use method1 (below) instead of method2 (below)? method1:: ..... int c; int digits[10]; ..... while ((c=getchar())!=EOF) { if (c>='0' && c<='9') { digits[c-'0']=digits[c-'0']+1; } } ....... method2: ...... int c; int digits[10]; ..... while ((c=getchar())!=EOF) { if (c>='0' && c<='9') { digits[c]=digits[c]+1; } } ...... Thanks in advance! p/s: this program is used to count the occurances of its digits from 0 to 9. Last edited by Alianto : April 5th, 2003 at 08:15 PM. |
|
#2
|
|||
|
|||
|
because you're dealing with integer numbers and charecters that happen to be numeric representations - there's a big difference between those two things.
0 is zero and '0' is on my computer in decimal is 48 i think. 0 and 48 are very different obviously. say you had '5'. it's decimal value is 53 on my computer (the reason i keep saying my computer is that the values can vary from computer to computer). 53 - 48 = 5 '5' - '0' = 5 so you're converting into the actual values that you want. real numbers. and the reason you don't use '5' - 48 is because of the possible variations on different computers so using '0' makes it much safer - doesn't matter which charecter encoding the computer is using it'll still work out. |
|
#3
|
|||
|
|||
|
I see. Now I know!
B'coz digit[c] is the same as digit[decimal_of_char_c]. Thanks Balance, Sorry for asking a silly question! Regards, Alianto |
|
#4
|
|||
|
|||
|
I am curious what variations in ASCII representations you have seen on different systems.
|
|
#5
|
|||
|
|||
|
i haven't come accross other char systems myself but apparentlyt hey do exist - so my book tells me. it'd be not called ascii though.
i guess it's pretty rare, but it's quite nice to know that whatever char system you're using '0's going to work. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > getchar() and array |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|