What are datafiles? Why would you need them?

Data files are simple text files that Turing can read and write from. Sometimes, especially in contests, the data entered will be in a text file rather than the user entering it when they run the program. In this tutorial, you will learn how to read from and write to data files.

Let's start with reading, which is used more often. You first declare an integer variable. This is required from Turing. Then, you'll use the open and get statements to read from it.

var inp : int %Turing requires this integer variable
var ctr : int := 0 %Counter variable, initial value 0
var tmp : string %Holds each line of the datafile

open : inp, "INPUT.txt", get %open the file INPUT.txt for reading

loop
     exit when eof(inp) %Exit when the end-of-file is reached
     ctr += 1
     
     get : inp, tmp %Read the [ctr]th line from the data file, and store it in the string variable tmp
     put ctr, "th line reads: ", tmp
end loop

You may have noticed eof in the above code. EOF means end-of-file, so we're telling Turing to exit the loop once it has reached the end of the file. If you don't do this, you'll get an error because Turing will try and read past the end of the file!


Loops · Procedures, functions, and processes