210 Chapter 10 Character Strings
Program 10.6 Output
This is a sample line of text.
This is a sample line of text.
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
runtime library routines
runtime library routines
The doloop in the readLinefunction is used to build up the input line inside the char-
acter array buffer. Each character that is returned by the getcharfunction is stored in
the next location of the array.When the newline character is reached—signaling the end
of the line—the loop is exited.The null character is then stored inside the array to ter-
minate the character string, replacing the newline character that was stored there the last
time that the loop was executed.The index number i – 1 indexes the correct position
in the array because the index number was incremented one extra time inside the loop
the last time it was executed.
The mainroutine defines a character array called linewith enough space reserved to
hold 81 characters.This ensures that an entire line (80 characters has historically been
used as the line length of a “standard terminal”) plus the null character can be stored
inside the array. However, even in windows that display 80 or fewer characters per line,
you are still in danger of overflowing the array if you continue typing past the end of the
line without pressing the Enter (or Return) key. It is a good idea to extend the
readLinefunction to accept as a second argument the size of the buffer. In this way, the
function can ensure that the capacity of the buffer is not exceeded.
The program then enters a forloop, which simply calls the readLinefunction three
times. Each time that this function is called, a new line of text is read from the terminal.
This line is simply echoed back at the terminal to verify proper operation of the func-
tion. After the third line of text has been displayed, execution of Program 10.6 is then
complete.
For your next program example (see Program 10.7), consider a practical text-process-
ing application: counting the number of words in a portion of text. Develop a function
called countWords, which takes as its argument a character string and which returns the
number of words contained in that string. For the sake of simplicity, assume here that a
word is defined as a sequence of one or more alphabetic characters.The function can
scan the character string for the occurrence of the first alphabetic character and consid-
ers all subsequent characters up to the first nonalphabetic character as part of the same
word. Then, the function can continue scanning the string for the next alphabetic
character, which identifies the start of a new word.