Search code examples
delphifiledelphi-2010

How do I read a row from a file that has both numbers and letters in Delphi 2010?


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)?


Solution

  • 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.