Page 1 of 1

retrieving strings from file

PostPosted: October 21st, 2008, 2:18 pm
by mac1234mac
Hello,

I'd like to learn how I could retrieve values of numbers and character
symbols from file, for example:
I have sequence of characters saved in txt file -
"numbers_and_symbols.txt":

abcd -1234.56 on

Particular parts of string are separated from each other by space.

I'd like to use, in Delphi program, string 'abcd' as string variable,
number -1234.56 as float variable
and 'on' as bool variable. How could I do it in Delphi 7.0?.

Cheers

PostPosted: October 21st, 2008, 5:15 pm
by Kambiz
There are some functions in SysUtils unit for converting strings to other data types. For example, StrToFloat converts a numerical string to double.

Of course, first you have to parse your text file to get each string token.

PostPosted: October 22nd, 2008, 6:55 am
by mac1234mac
But if I have string in a file, how can I load it to string variable in Delphi 7.0?. For example: I've got string 'abcd' placed in the first line of the
file named 'text.txt'. How can I retrieve it so I would have string
variable in program: s:='abcd'?.

Thank You for answer.

PostPosted: October 22nd, 2008, 7:15 am
by Kambiz
Look at this piece of code:

Code: Select all
var
  Lines: TStringList;
  I: Integer;
  Line: String;
begin
  Lines := TStringList.Create;
  try
    Lines.LoadFromFile('path\to\your\file.txt');
    for I := 1 to Lines.Count do
    begin
      Line := Lines[I];
      /*
        Here you have access to each line of your text file using the Line variable.
      */
    end;
  finally
    Lines.Free;
  end;
end;