跳轉到內容

Turing/資料檔案

來自華夏公益教科書,開放書籍,開放世界

什麼是資料檔案?為什麼需要它們?

資料檔案是Turing可以讀取和寫入的簡單文字檔案。有時,特別是在比賽中,輸入的資料將儲存在文字檔案中,而不是使用者在執行程式時輸入。在本教程中,您將學習如何讀取和寫入資料檔案。

讓我們從更常用的讀取開始。首先,您需要宣告一個整型變數。這是Turing的要求。然後,您將使用openget語句來讀取資料。

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

您可能已經注意到上面的程式碼中的eof。EOF表示檔案結束,因此我們在告訴Turing一旦它到達檔案末尾就退出迴圈。如果您不這樣做,您將收到一個錯誤,因為Turing將嘗試讀取檔案末尾之後的資料!


迴圈 · 過程、函式和程序

華夏公益教科書