ascii review

ascii review - val = (49-48)*100 + (50-48)*10 + (52-48);...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
ASCII Review Let’s watch this  program in action – it  converts a short string  of ASCII digits into an  integer. int StringToInt(string n) { int val; if (n.length() == 1) val = n[0] – ‘0’; else if (n.length == 2) val = (n[0]-’0’) * 10 + (n[1]–‘0’); else if (n.length == 3) val = (n[0]-’0’) * 100 + (n[1]–‘0’) * 10 + (n[2]-’0’); return(val); } int main(void) { int result; string s = “124"; result = StringToInt(s); cout << result; } result     s “124” n “124”     val     124 124 val = (‘1’-’0’)*100 + (‘2’-’0’)*10 + (‘4’-’0’);
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: val = (49-48)*100 + (50-48)*10 + (52-48); 124 Function Review Heres a more general version that will work for strings of any length. int StringToInt(string s) { int i, total=0, mult=1, temp; for (i=s.length()-1; i >= 0; i--) { temp = s[i] 0; temp *= mult; total += temp; mult *= 10; } return(total); } void main() { int result; string s = "670"; result = StringToInt(s); cout << result; } However, it still wont handle negative numbers!...
View Full Document

This note was uploaded on 05/11/2011 for the course CS 33 taught by Professor Rohr during the Spring '08 term at UCLA.

Page1 / 2

ascii review - val = (49-48)*100 + (50-48)*10 + (52-48);...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online