1

我正在尝试编写一个程序来阅读一长串书籍(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.

谁能帮忙解决问题??

4

1 回答 1

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值)。您应该尝试添加一些代码,使其对输入文件中的问题更具弹性。正如其他人指出的那样,可能有更好的方法来构建输入并读取它。

于 2013-08-06T17:17:24.653 回答