gpt4 book ai didi

delphi - 在Delphi中将.txt文件中的Double数据读取到数组中

转载 作者:行者123 更新时间:2023-12-03 15:38:33 25 4
gpt4 key购买 nike

我是 Delphi 编码新手,在读取 .txt 文件方面遇到困难。我试图从 .txt 文件中读取输入数据(选项卡式 double ),其中每一列都被视为变量(日、温度、压力……),每一行都被视为时间步长(小时)。我如何将此数据读入数组,以便对这些变量进行每小时计算(逐行)?

非常感谢您的建议!

输入示例(.txt 文件中的选项卡式 double ):

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.

最佳答案

我会使用 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;

虽然您的标题将数据描述为整数,但它似乎是整数和 float 的混合。不管怎样,我认为你应该能够填补空白并填充动态值数组,处理错误检查等等。

关于delphi - 在Delphi中将.txt文件中的Double数据读取到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9975875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com