Getting Started

(lily) #1

Chapter 5: C Control Flow


I to integer, function converts a string of ASCII characters

not equal to or between ‘0’ and ‘9’. This gets us out of the loop, but not out of
a robust function, we would have some kind of error reporting
so that code calling atoi could know that it sent a bad string and so the
alling function could build in some way to recover. We’ll get into all that later

he conversion algorithm relies on the convenient fact that the ASCII characters
n ASCII, ‘1’ is
ter, we get (s[i] – ‘0’) = 1, the integer.
has a value of 0x30 from the character
’ which has a value of 0x31, leaving us with the number 1. Voila: ASCII to
teger.

the 10*n = 0 and the character is
e integer. For each subsequent pass, the n has a
ultiplied by 10 providing the 10’s, 100’s, and so forth.

e concerned if yours wasn’t as simple and elegant as this one. Mine
art thinking like a computer. Then your brain turns to
.

e characters in an array. How would
u do is? T puter, then look at the reverse

NOTE unction

}

T

re


he atoi, ASCI
presenting the integers 0 thru 9 into an integer number equivalent to the string.
If you didn’t figure this one out yourself then use your paper and pencil computer
to run the function with char s[] equaling ‘1,2,3,4,\0’ to see how it works. Note the
condition in the ‘for’ statement will cause the loop to bail if one of the characters
is
trouble. In
mechanism
c
and be careful not to make mistakes now. (Famous last words)


T
for integers are represented by a sequence of numbers. ‘0’ is 0x30 i
0x31, and so on. So if s[i] = ‘1’, the charac
That is, we subtract the character ‘0’ which
‘1
in


We start with n = 0, so the first time thru
converted to the 1’s position in th
value so it gets m


You were asked to think about this algorithm before looking at the atoi function.
Don’t b
wasn’t. It takes a while to st
silicon and people avoid you


Now think about the problem of reversing th
yo th ry it on the pencil and paper com
function.


// : stolen from K&R p. 62 reverse f
// reverse: reverse a string s in place
void reverse(char s[])
{
int c, i, j;
Free download pdf