19.12.2012 Views

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

136 <strong>Computer</strong> <strong>Programming</strong> <strong>Concepts</strong> <strong>and</strong> <strong>Visual</strong> <strong>Basic</strong><br />

■ EOF FUNCTION<br />

Data to be processed are often retrieved from a file by a Do loop. <strong>Visual</strong> <strong>Basic</strong> has a useful<br />

function, EOF, that tells us if we have reached the end of the file from which we are reading.<br />

Suppose a file has been opened with reference number n. At any time, the condition<br />

EOF(n)<br />

will be true if the end of the file has been reached, <strong>and</strong> false otherwise.<br />

One of the first programs I wrote when I got my computer stored a list of names <strong>and</strong><br />

phone numbers <strong>and</strong> printed a phone directory. I first had the program display the directory<br />

on the screen <strong>and</strong> later changed the picNumbers.Print statements to Printer.Print statements<br />

to produce a printed copy. I stored the names in a file so I could easily add, change, or delete<br />

entries.<br />

EXAMPLE 1<br />

The following program displays the contents of a telephone directory. The names <strong>and</strong> phone numbers are<br />

contained in the file PHONE.TXT. The loop will repeat as long as the end of the file is not reached.<br />

PHONE.TXT contains the following four lines:<br />

“Bert”, “123-4567”<br />

”Ernie”, “987-6543”<br />

”Grover”, “246-8321”<br />

”Oscar”, “135-7900”<br />

Object Property Setting<br />

frmPhone Caption Directory<br />

cmdDisplay Caption Display Phone Numbers<br />

picNumbers<br />

Private Sub cmdDisplay_Click()<br />

Dim nom As String, phoneNum As String<br />

picNumbers.Cls<br />

Open “PHONE.TXT”For Input As #1<br />

Do While Not EOF(1)<br />

Input #1, nom, phoneNum<br />

picNumbers.Print nom, phoneNum<br />

Loop<br />

Close #1<br />

End Sub<br />

[Run, <strong>and</strong> press the comm<strong>and</strong> button.]<br />

The program in Example 1 illustrates the proper way to process a list of data contained in a<br />

file. The Do loop should be tested at the top with an end-of-file condition. (If the file is empty,<br />

no attempt is made to input data from the file.) The first set of data should be input after the<br />

Do statement, <strong>and</strong> then the data should be processed. Figure 5-3 contains the pseudocode <strong>and</strong><br />

flowchart for this technique.

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

Saved successfully!

Ooh no, something went wrong!