Author: Jonas Bilinkevicius
How to parse a line from a comma-separated file into a record
Answer:
1 { ... }
2 type
3 TRec = record
4 lastname, firstname: string[30];
5 age: Integer;
6 position: string[40];
7 salary: Single;
8 end;
9
10 procedure ParseLine(const Line: string; var rec: TRec);
11 var
12 i, start, field: Integer;
13
14 procedure CopyField(currPos: Integer);
15 var
16 len, err: Integer;
17 temp: string;
18 begin
19 len := currpos - start;
20 if len > 0 then
21 begin
22 temp := Copy(Line, start, len);
23 err := 0;
24 with rec do
25 case field of
26 0: lastname := temp;
27 1: firstname := temp;
28 2: Val(temp, age, err);
29 3: position := temp;
30 4: Val(temp, salary, err)
31 else
32 { too much data in this line, issue error message }
33 end;
34 if err <> 0 then
35 begin
36 {issue error message}
37 end;
38 end
39 else
40 {no data in this field, issue error message or leave the default }
41 end;
42
43 begin
44 {set defaults for the fields, init variables}
45 FillChar(rec, sizeof(rec), 0);
46 field := 0; {fields keeps track of which field to fill next}
47 start := 1; {fencepost for start of field data}
48 for i := 1 to Succ(Length(Line)) do
49 begin
50 if i > Length(Line) then
51 begin
52 {copy the last section of the line to the last field}
53 CopyField(i);
54 end
55 else
56 {test for separator character} if Line[i] = ',' then
57 begin
58 {found one, copy data from current fencepost to this separator}
59 CopyField(i);
60 {advance fencepost to position after separator}
61 start := i + 1;
62 {next field}
63 Inc(field);
64 end;
65 end;
66 end;
|