Search code examples
while-looppascalreadfileeof

pascal file read loop always read extra line in the end


I'm learning about using pascal to read integers from text file. The program should read and print 10 integers, but the it actually printed 11 values which it printed extra 0 in the end. I used to meet the same problem when I writing c++ program, but I solved it by using while(inFile >> num) instead of while(!EOF{infile >> num;}. Here is the pascal code for my program:

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.

Solution

  • First, the file obviously has a Carriage Return, Line feed (CRLF) pair also after the last line, which is ok, but if there wouldn't have been one, you would not have seen the problem.

    You need to know that you can read std input or files with, either read() or readln(). read() doesn't remove the CRLF from end of lines, which means the eof (end of the file) is not actually true when you read the last number from the file.

    To correct your program, use readln() instead of read()

    You can read more about the differences between read() and readln() here