Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
April 5th, 2003, 09:10 PM
 Alianto
Contributing User

Join Date: Oct 2002
Posts: 61
Time spent in forums: 9 m 2 sec
Reputation Power: 12
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;
}
}
......

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 09:15 PM.

#2
April 5th, 2003, 10:45 PM
 balance
.

Join Date: Dec 2002
Posts: 296
Time spent in forums: < 1 sec
Reputation Power: 11
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
April 5th, 2003, 11:06 PM
 Alianto
Contributing User

Join Date: Oct 2002
Posts: 61
Time spent in forums: 9 m 2 sec
Reputation Power: 12
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
April 6th, 2003, 03:37 AM
 3dfxMM
Contributing User

Join Date: Aug 2002
Posts: 272
Time spent in forums: 6 Days 17 h 57 m 24 sec
Reputation Power: 18
I am curious what variations in ASCII representations you have seen on different systems.

#5
April 6th, 2003, 07:08 AM
 balance
.

Join Date: Dec 2002
Posts: 296
Time spent in forums: < 1 sec
Reputation Power: 11
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