Reading Double data from .txt files into arrays in Delphi
I am new to Delphi coding and am struggling with reading .txt files. I am trying to read input data (double tabbed) from a .txt file where each column is treated as a variable (Day, Temperature, Pressure, ...) and each row is treated as a time step (hour). How can I read this data in an array so that I can do hourly calculations on these variables (in turn)?
Thank you so much for any advice!
Input sample (Doubles tabs in .txt file):
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
What I have so far (VCL Form Application):
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.
source to share
Delphi still has a very old (styled) pascal read routine for text variables so you can read into your array directly :)
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;
source to share
I would do this using to parse the TStringList
file in strings and SplitString
to tokenize each divisible value.
First of all, to load the file into a list of lines:
var
Strings: TStringList;
....
Strings := TStringList.Create;
try
Strings.LoadFromFile(FileName);
ProcessStrings(Strings);
finally
Strings.Free;
end;
And then actually process the lines:
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;
Although your title describes the data as an integer, it appears to be a mixed integer and floating point. Anyway, I think you should fill in the blanks and populate your dynamic value arrays, handle error checking, etc.
source to share