228 Chapter 10 Character Strings
can be used to print out the value that is used to internally represent the character stored
inside c. If your system uses ASCII, the statement
printf ("%i\n", 'a');
displays 97, for example.
Tr y to predict what the following two statements would produce:
c = 'a' + 1;
printf ("%c\n", c);
Because the value of 'a'is 97 in ASCII, the effect of the first statement is to assign the
value 98 to the character variable c.Because this value represents the character 'b'in
ASCII, this is the character that is displayed by the printfcall.
Although adding one to a character constant hardly seems practical, the preceding
example gives way to an important technique that is used to convert the characters '0'
through '9'into their corresponding numerical values 0 through 9. Recall that the
character '0'is not the same as the integer 0, the character '1'is not the same as the
integer 1, and so on. In fact, the character '0'has the numerical value 48 in ASCII,
which is what is displayed by the following printfcall:
printf ("%i\n", '0');
Suppose the character variable ccontains one of the characters '0'through '9'and that
you want to convert this value into the corresponding integer 0 through 9. Because the
digits of virtually all character sets are represented by sequential integer values, you can
easily convert cinto its integer equivalent by subtracting the character constant '0'from
it.Therefore, if iis defined as an integer variable, the statement
i = c - '0';
has the effect of converting the character digit contained in cinto its equivalent integer
value. Suppose ccontained the character '5',which, in ASCII, is the number 53.The
ASCII value of '0'is 48, so execution of the preceding statement results in the integer
subtraction of 48 from 53, which results in the integer value 5 being assigned to i.On a
machine that uses a character set other than ASCII, the same result would most likely be
obtained, even though the internal representations of '5'and '0'might differ.
The preceding technique can be extended to convert a character string consisting of
digits into its equivalent numerical representation.This has been done in Program 10.11
in which a function called strToIntis presented to convert the character string passed
as its argument into an integer value.The function ends its scan of the character string
after a nondigit character is encountered and returns the result back to the calling rou-
tine. It is assumed that an intvariable is large enough to hold the value of the converted
number.