Паскаль: Ошибка команды длины строки Delphi - PullRequest
2 голосов
/ 28 марта 2011

Я пишу часть кода для чтения в файлах CSV и анализа информации из них (в настоящее время у меня есть только начальная часть кода, которая будет читаться в заголовках в начале файла. Когда я пытаюсь Скомпилируйте этот код Я получаю сообщение об ошибке в строке, которая берет длину строки из файла.

Я получаю сообщение об ошибке: [Ошибка] MCLRandomizer.pas (*): отсутствует оператор или точка с запятой

while not EOF(csvFile) do begin
        i :=0;
        ReadLn(csvFile, line);
        if lineOne = true then begin
          length := Length(line);               //error here
          while length > 0 do begin
            dx := Pos(',', line);
            buffer := Copy(line, 0, dx-1);
            headers[i] := buffer;
            line := Copy(line, dx+1, length);   
            length := Length(line);             //error here
          end;
          lineOne := false;
        end;
      end;

Ответы [ 4 ]

11 голосов
/ 28 марта 2011

Паскаль не делает различий между длиной и длиной ... они оба ДЛИНА

Переименуйте переменную, она испортит функцию.

3 голосов
/ 28 марта 2011

FTR: Если вы действительно, действительно хотите, вы можете написать

length := System.Length(line);

(при условии, что length является целым числом). Я согласен с другими авторами, что это было бы плохой идеей.

2 голосов
/ 09 декабря 2011

Решение, которое я разработал для чтения файла csv в структуру записи (фактически массив структур записей), представляет собой

program read_file_into_array_of_records;

{$APPTYPE CONSOLE}

uses
  SysUtils, StrUtils;



type
    Tscore = record
                name : string [25];
                marks : integer;
              end;

var
    input_file: TextFile;
    file_record : string[100];
    score : array [0..3] of Tscore;
    index : integer;



// function that returns all text up to a comma or the end of the line
function get_value() : string;
var
    comma_pos: integer;
    value: string[100];
begin


    comma_pos := Pos(',', file_record);

    // if comma found cut out all text up to it
    if comma_pos <> 0 then
    begin


        value := leftstr(file_record, comma_pos - 1);


        delete(file_record, 1, comma_pos);
    end
    else
    begin

        // no comma found so just take everything that remains
        value := file_record;
    end;

    get_value := value;


end;


// procedure to fill one record by breaking up the comma separated values
procedure fill_record (index: integer);
begin

    // call the function get_value as many times as needed to get
    // each comma separated value
    score[index].name := get_value();
    score[index].marks := strtoint(get_value());
end;


// procedure to fill array with contents of csv file
procedure fill_array ();
begin


    index := 0;



    while not EoF(input_file) do
    begin


        readln(input_file, file_record);


        fill_record (index);


        index := index + 1;
    end;


end;


// procedure to display contents of array
procedure display_array ();
begin



    for index := 0 to 3 do
    begin


        writeln(score[index].name, ' got ', score[index].marks, ' marks' );
    end;

    readln;

end;


// main prog

begin

    assignfile(input_file, 'scores.csv');

    reset(input_file);

    fill_array ();

    closefile(input_file);

    display_array();

end.

содержимое файла Scores.csv:

Джеймс, 31
Джейн, 23
Тоби, 34
Руфь, 40

0 голосов
/ 30 марта 2011

Более того, строки Паскаля равны 1, а не 0. (оператор copy ())

...