2000 Jan 19
In many cases, a program's input is line-based. That is, every input line has the same format. We present two programming patterns to deal with line-based input.
I define line-based input as input that consists of lines each having similar format. For example, a file may consist of lines each containing a name and age. Another input may consist of lines of text. Another input may have lines with a name, beginning hours, and ending hours.
If the input is line-based, usually the program consists of processing each line and optionally printing output per line.
Suppose we wish to determine the name of the oldest person given line-based input of name and age. As each line is read, we compare the age of the oldest person seen so far with the age specified on the line, updating the age and associated name if the line's age is larger.
Consider writing a program to count the number of characters and lines in a file. We can read the entire line (not the line's fields), incrementing the number of lines seen so far and augmenting the character count by the number of characters on that line.
I currently can conceive of two large classes of line-based input:
Consider our example of computing the name of the oldest person given a list of lines each having a name and an age.
Here is an example program: oldest.cc. The important part of the program is the while loop. Since each line has two fields, the input in the loop's conditional will have two variables, one for each field. In the body, we process the line. The code after the loop is executed only after all of the input has been read.2
Here are rules for this pattern:
For this pattern, we do not break the line into fields. For example, the program counting the number of characters and lines in a file need not break the line into fields.
Here is an example program: count.cc. The important part of the program is the while loop. Each line is read using the getline() function. In the body, we process the line. The code after the loop is executed only after all of the input has been read.
Here are the rules for this pattern: