pascal 文件读取循环总是在最后读取额外的行

pascal file read loop always read extra line in the end

我正在学习如何使用 pascal 从文本文件中读取整数。该程序应该读取并打印 10 个整数,但它实际上打印了 11 个值,最后打印了额外的 0。我以前在写c++程序的时候遇到过同样的问题,但是我用while(inFile >> num)而不是while(!EOF{infile >> num;}解决了。 这是我程序的 Pascal 代码:

program testRead;
uses crt;
var
    nSize : integer;
    num, sum : longint;
    root : real;
    f : text;
begin
    assign(f, 'numbers.txt');
    reset(f);

    nSize := 0;

    while not eof(f) do
    begin
            read(f, num);
            writeln(num);
    end;

    close(f);
end.

首先,该文件显然在最后一行之后也有一个 Carriage Return, Line feed (CRLF) 对,这没关系,但如果没有,你就不会看到问题。

您需要知道您可以使用 read()readln() 读取标准输入或文件。 read() 不会从行尾删除 CRLF,这意味着当您从文件中读取最后一个数字时,eof(文件末尾)实际上并不正确。

要更正您的程序,请使用 readln() 而不是 read()

您可以阅读更多关于 read()readln() 之间的区别