从文件读取数组时的Pascal运行时错误(范围溢出)

时间:2013-08-06 11:31:27

标签: arrays file pascal

我正在尝试编写一个程序来阅读一长串书(1000本书),isbn等 但是当程序运行时,它会显示范围超限 txt的格式是

1
1234567890
ABC book
peter
20
2
1234567896
...

代码是:

const maxbk=1000;
type bookrecord = record
                    book_no:string;
                    isbn:string;
                    book_name:string;
                    author:string;
                    borrowed:string;
                    end;
var booklist : array[1..maxbk] of bookrecord;totalbook:integer;

procedure readbooklist(var bklist:array of bookrecord;var totalbk:integer);
var f:text;temp:string;code:integer;
begin
  totalbk:=0;
  assign(f,'bklist.txt');
  reset(f);
  while not eof(f) do
  begin
    readln(f,bklist[totalbk+1].book_no);
    readln(f,bklist[totalbk+1].isbn);
    readln(f,bklist[totalbk+1].book_name);
    readln(f,bklist[totalbk+1].author);
    readln(f,bklist[totalbk+1].borrowed);
    totalbk:=totalbk+1;
  end;
  close(f);
  writeln('read file done');
end;

begin
  readbooklist(booklist,totalbook);
end.

谁可以帮助解决问题?

1 个答案:

答案 0 :(得分:1)

我认为问题在于你对数组参数的处理。试试这个(以粗体突出显示我添加的更改):

const maxbk=1000;
type bookrecord = record
                    book_no:string;
                    isbn:string;
                    book_name:string;
                    author:string;
                    borrowed:string;
                    end;

var booklist : array[1..maxbk] of bookrecord; totalbook:integer;

procedure readbooklist(var bklist:array of bookrecord;var totalbk:integer);
var f:text;temp:string;code:integer;
begin
  totalbk:=Low(bklist);
  assign(f,'bklist.txt');
  reset(f);
  while not eof(f) do
  begin
    readln(f,bklist[totalbk].book_no);
    readln(f,bklist[totalbk].isbn);
    readln(f,bklist[totalbk].book_name);
    readln(f,bklist[totalbk].author);
    readln(f,bklist[totalbk].borrowed);
    totalbk:=totalbk+1;
  end;
  totalbk := totalbk - Low(bklist);
  close(f);
  writeln('read file done');
end;

begin
  readbooklist(booklist,totalbook);
end.

此外,一些选择空间有助于提高可读性(例如每个逗号后面的空格和赋值运算符周围的空格)。

另请注意,您的代码(以及我提供的更改的代码)不会检查输入文本文件中的不完整记录或正确检查空行等(例如,无效的book_no值)。您应该尝试添加一些代码,使其对输入文件中的问题更具弹性。正如其他人所指出的那样,可能有更好的方法来构建输入并读取它。