How do I read a row from a file that has both numb

2019-08-16 21:14发布

I have a text file that has, on any given row, data that are expressed both in text format and in numeric format. Something like this:

Dog 5 4 7

How do I write a file reading routine in Delphi that reads this row and assigns the read values into the correct variables ("Dog" into a string variable and "5", "4" and "7" into real or integer variables)?

3条回答
贼婆χ
2楼-- · 2019-08-16 21:52

You can use SplitString from StrUtils to split the string into pieces. And then use StrToInt to convert to integer.

uses
  StrUtils;
....
var
  Fields: TStringDynArray;
....
Fields := SplitString(Row, ' ');
StrVar := Fields[0];
IntVar1 := StrToInt(Fields[1]);
IntVar2 := StrToInt(Fields[2]);
IntVar3 := StrToInt(Fields[3]);

And obviously substitute StrToFloat if you have floating point values.

查看更多
姐就是有狂的资本
3楼-- · 2019-08-16 22:07

You can use File of TRecord, with TRecord. For example:

type TRecord = packed record
  FName : String[30];
  Val1: Integer;
  Val2: Integer;
  Val3: Integer;
end;

And simple procedure:

procedure TMainForm.Button1Click(Sender: TObject);
var
  F: file of TRecord;
  Rec : TRecord;
begin
  AssignFile(F, 'file.dat');
  try
    Reset(F);
    Read(F, Rec);
  finally
    CloseFile(F);
  end;
end;
查看更多
三岁会撩人
4楼-- · 2019-08-16 22:11

Take TJclStringList from Jedi Code Library.

On 1st step you take one list and do .LoadFromFile to split the file to rows. On second step you iterated through those rows and set secondary stringlist by those lines with space as delimiter. Then you iterate through secondary string list and do what u want.

Like that

var slF, slR: IJclStringList; ai: TList<integer>; s: string; i: integer;
    action: procedure(const Name: string; Const Data: array of integer);

slF := TJclStringList.Create; slF.LoadFromFile('some.txt');
slR := TJclStringList.Create;
for s in slF do begin
    slR.Split(s, ' ', true);
    ai := TList<Integer>.Create;
    try
       for i := 1 to slR.Count - 1 do
           ai.Add(StrToInt(slR[i]));
       action(slR[0], ai.ToArray);
    finally ai.Free; end;
end; 
查看更多
登录 后发表回答