08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 6 ■ Characters

Exercise: Modify Program P6.12 to send the output to a file, linecopy.txt.

Exercise: Write a program to copy the contents of a file, input.txt, to a file, copy.txt.

Hint: you just need to make minor changes to Program P6.10.

6.11 Convert Digit Characters to Integer

Let us consider how we can convert a sequence of digits into an integer. When we type the

number 385, we are actually typing three individual characters – ‘3’ then ‘8’ then ‘5’. Inside the

computer, the integer 385 is completely different from the three characters ‘3’ ‘8’ ‘5’. So when we

type 385 and try to read it into an int variable, the computer has to convert this sequence of three

characters into the integer 385.

To illustrate, the 8-bit ASCII codes for the characters ‘3’, ‘8’, and ‘5’ are 00110011, 00111000,

and 00110101, respectively. When typed to the screen or a file, the digits 385 are represented

by this:

00110011 00111000 00110101

Assuming an integer is stored using 16 bits, the integer 385 is represented by its binary

equivalent

0000000110000001

Observe that the character representation is quite different from the integer representation.

When we ask scanf (or fscanf) to read an integer that we type, it must convert the character

representation to the integer representation. We now show how this is done.

The basic step requires us to convert a digit character into its equivalent integer value.

For example, we must convert the character ‘5’ (represented by 00110101) into the integer 5

(represented by 0000000000000101).

Assuming that the codes for the digits 0 to 9 are consecutive (as they are in ASCII and other

character sets), this can be done as follows:

integer value of digit = code for digit character – code for character ‘0’

For example, in ASCII, the code for ‘5’ is 53 and the code for ‘0’ is 48. Subtracting 48 from 53

gives us the integer value (5) of the character ‘5’. Once we can convert individual digits, we can

construct the value of the number as we read it from left to right, using the following algorithm:

set num to 0

get a character, ch

while ch is a digit character

convert ch to the digit value, d = ch - '0'

set num to num*10 + d

get a character, ch

endwhile

num now contains the integer value

161

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!