我是熟悉Delphi编码和读取.txt文件的新手。我试图从.txt文件中读取输入数据(选项卡式双打),其中每列都被视为变量(日,温度,压力......),每一行都被视为时间步长(小时)。如何将这些数据读入数组,以便用这些变量进行每小时计算(逐行)?
非常感谢您的任何建议!
输入样本(.txt文件中的选项卡式双打):
1 0.5 0 -12.6 -1.39 100 -19.5 0 3.3
1 1 0 -12.6 -1.43 100 -19.8 0 3.3
1 1.5 0 -12.7 -1.51 99.9 -20.5 0 3.2
到目前为止(VCL表格申请):
var // Declaration of variables
Read: TRead;
i:Byte;
data:array of array of Integer; //Creation of dynamic array (adapts --> Setlength() command)
Input:TextFile;
Location:String;
Counter:Integer;
Maximum:Integer;
procedure TRead.Button1Click(Sender: TObject); // Button "Read" command
begin
Location:=Edit1.Text; // Path of inputfile from Form
AssignFile(Input,(Location+'\Test1.txt')); // Assigning inputfile
Reset(Input); // Open for read-write
If (IoResult = 0) Then Begin // If Inputfile reading was succesful...
Counter:=1;
While Not EoF(Input) Do Begin
ReadLn(Input,i);
Data[Counter]:=i;
If EoF(Input) Then Break;
Inc(Counter); //increase 'Counter' by 1
End;
End
Else WriteLn('Error when reading the file')
CloseFile(Input);
End;
Begin
For i:=1 To 10 Do WriteLn(data[i]);
ReadLn;
End.
答案 0 :(得分:10)
我会使用TStringList
将文件解析为行,SplitString
来标记每个分隔值。
首先将文件加载到字符串列表中:
var
Strings: TStringList;
....
Strings := TStringList.Create;
try
Strings.LoadFromFile(FileName);
ProcessStrings(Strings);
finally
Strings.Free;
end;
然后实际处理字符串:
procedure ProcessStrings(Strings: TStrings);
var
line, item: string;
items: TStringDynArray;
value: Double;
begin
for line in Strings do
begin
items := SplitString(line, #9#32);//use tab and space as delimiters
for item in items do
begin
value := StrToFloat(item);
//do something with value
end;
end;
end;
虽然您的标题将数据描述为整数,但它似乎是混合整数和浮点数。无论如何,我认为你应该能够填补空白并填充动态数组值,处理错误检查等等。
答案 1 :(得分:5)
Delphi仍然具有非常古老的(塑造的)文本变量的pascal读取过程,因此您可以直接读取数组:)
Var NumArray: Array[1..9] of double; // you have 9 variables
while not eof(F) do begin
read(F,NumArray[1],NumArray[2],NumArray[3],NumArray[4],NumArray[5],NumArray[6],NumArray[7],NumArray[8],NumArray[9]);
// store it somewhere;
end;