簡體   English   中英

從Delphi 7中的文本文件加載信息

[英]Loading information from a text file in Delphi 7

我試圖用一個程序將名稱和分數保存到文本文件中,然后從另一個程序中的文件中加載它。 問題在於引用每個名稱而不是僅加載整個文件或僅加載名字。

它保存為:

scores = record
        name: string[20];
        Score: integer;

procedure TForm1.BtnSaveClick(Sender: TObject);
var
scoresFile: file of scores;
begin
scoresrecord.name := EdtName.Text;
scoresrecord.Score := Score;
assignfile(scoresFile, 'Teacher.txt');
rewrite(scoresFile);
write(scoresFile, scoresrecord);
closeFile(scoresFile);
end; 

並使用以下方法加載到字符串網格中

 scores = record
        name: string[20];
        Score: integer;

var 
ScoreRecord: scores;
scoresFile: file of scores;

StrGrdScores.Cells[0,0]:='Name';
StrGrdScores.Cells[1,0]:='Score';
assignfile(scoresFile, 'C:\Computing\AlgebraNew\Teacher.txt');
reset(scoresFile);
while not Eof(scoresFile) do
read(scoresFile, ScoreRecord);
closeFile(scoresFile);
for I := 1 to StrGrdScores.Row do
StrGrdScores.cells[0,i]:=ScoreRecord.name;

這是我嘗試加載名稱,但它只是將文件中的第一個名稱加載到每一行。 當我弄清楚如何加載名稱時,加載分數應該是顯而易見的。 任何幫助深表感謝。

您的保存過程似乎只將一條記錄保存到文件中。

您的加載過程將每一行讀入同一個變量,覆蓋以前的值。 在從文件中讀取值時將值寫入網格。

i = 0;
while not Eof(scoresFile) do
begin
  read(scoresFile, ScoreRecord);
  StrGrdScores.cells[0,i]:=ScoreRecord.name;
  StrGrdScores.cells[1,i]:=ScoreRecord.Score;
  inc(i);
end;
closeFile(scoresFile);

在寫入值之前,您可能需要向stringgrid追加一行。

assignfile / write / rewrite / closefile是非常舊式的Pascal。 在Object Pascal中,特別是Delphi中,有一個TFileStream對象可供使用。 但在這個特定的情況下,我會建議TStringList對象。 它具有LoadFromFile和SaveToFile方法,但也有索引屬性Value,它將值存儲在具有“Name = Value”的行中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM