Input Line by Line

In concept, inputting data from a file is identical to inputting from the user.  In practice, several issues can make file input more complicated.

 

Line-Oriented Input

 

When a file is used for input, an Input symbol consumes exactly one line of the file.  The contents of the line determine whether Raptor interprets it as a string or a number (see String vs. Numeric Input).  Therefore, a text file created for input must have the desired number of lines to match the number of inputs to be performed.  Further, each of these lines must make sense for the variable that is to input that line of data.  For example, a file containing information on a single cadet might have the following lines:

 

C4C John Doe

28

3.51

 

The data in this file can be read using three Input symbols.  The first Input symbol to be executed should give a value to a variable called something like cadet_name.  The second should give a value to a variable like squadron.  The third Input symbol should give a value to a variable like GPA.  If these Input symbols are executed out of order, the program will be working with meaningless data.  

 

Notes:   An empty line in a file, when consumed by an Input symbol, will give an empty string (that is, a string with no characters in it) to the input variable.  If an Input symbol is executed after the last line of a file has been consumed, a run-time error occurs.

 

Files of Unknown Size (Advanced Topic)

 

Sometimes programs read from a file without knowing in advance how many lines are in the file.  In such cases, the programmer must have a way to know when the end of the data has been reached.  Raptor provides a function called End_Of_Input that returns true if all lines in a file have been consumed, false otherwise.  End_Of_Input will normally be used in the diamond symbol to exit a loop.

 

Note:  If editing a file by hand using Notepad or some other editor, be sure not to leave extra blank lines at the bottom of the file.  When the file is input in a loop that exits when End_Of_Input is true, these blank lines will be consumed by Raptor as empty strings.  The result is that the last few values input will be meaningless (or, if they are going into numeric variables (like array elements), they will cause a run-time error).

 

Example

 

Below is a Raptor program that inputs from a file until End_Of_Input is true.  Note the slightly different structure of the loop.  With count initialized to zero and the exit at the top of the loop, we guarantee that, upon loop exit, count contains exactly the number of values input (and it could even be 0, given an empty file).