Note: When I wrote this answer, the question claimed that multiple values appeared in a single line, separated by spaces. Apparently that information was wrong.
There are multiple parts to this question. Please do read this answer in consultation with the documentation. Some hopefully useful tips on doing that can be found here: How can I search for Delphi documentation?
Reading a file
Lots of ways to do this. Perhaps the simplest and most common approach is to use a TStringList
. Create one, and call LoadFromFile
passing the name of your text file.
Splitting the string
Again, plenty of options. I'd probably go for a split function like StrUtils.SplitString
.
If you have a string str
containing the space-delimited values you would do the following:
var
Values: TStringDynArray;
....
Values := SplitString(str, ' ');
Of course, it now looks like you have one value per line of the file. In which case you don't need to split any strings.
Converting values from string to real
Use StrToFloat
for this.
var
RealValue: Real;
....
RealValue := StrToFloat(StringValue);
This will use the locale settings of the local user. That might give you a headache if there's a mismatch with the decimal separators. If the decimal separator is always going to be, for instance, .
, then you need to specify that.
var
RealValue: Real;
FormatSettings: TFormatSettings;
....
FormatSettings := TFormatSettings.Create;
FormatSettings.DecimalSeparator := '.';
RealValue := StrToFloat(StringValue, FormatSettings);
If StrToFloat
fails for any reason it will raise an exception. As an alternative you can use TryStrToFloat
which indicates failure using its Boolean
return value. For example:
if not TryStrToFloat(StringValue, RealValue, FormatSettings) then
.... deal with error