2006. március 13., hétfő
How to parse a line from a comma-separated file into a record
Problem/Question/Abstract:
How to parse a line from a comma-separated file into a record
Answer:
{ ... }
type
TRec = record
lastname, firstname: string[30];
age: Integer;
position: string[40];
salary: Single;
end;
procedure ParseLine(const Line: string; var rec: TRec);
var
i, start, field: Integer;
procedure CopyField(currPos: Integer);
var
len, err: Integer;
temp: string;
begin
len := currpos - start;
if len > 0 then
begin
temp := Copy(Line, start, len);
err := 0;
with rec do
case field of
0: lastname := temp;
1: firstname := temp;
2: Val(temp, age, err);
3: position := temp;
4: Val(temp, salary, err)
else
{ too much data in this line, issue error message }
end;
if err <> 0 then
begin
{issue error message}
end;
end
else
{no data in this field, issue error message or leave the default }
end;
begin
{set defaults for the fields, init variables}
FillChar(rec, sizeof(rec), 0);
field := 0; {fields keeps track of which field to fill next}
start := 1; {fencepost for start of field data}
for i := 1 to Succ(Length(Line)) do
begin
if i > Length(Line) then
begin
{copy the last section of the line to the last field}
CopyField(i);
end
else
{test for separator character} if Line[i] = ',' then
begin
{found one, copy data from current fencepost to this separator}
CopyField(i);
{advance fencepost to position after separator}
start := i + 1;
{next field}
Inc(field);
end;
end;
end;
Feliratkozás:
Megjegyzések küldése (Atom)
Nincsenek megjegyzések:
Megjegyzés küldése