Reading integer numbers in Pascal

13,093

Solution 1

From what I can recall read literally reads the file as a stream of characters, of which a blank space and carriage return are, but I believe these should be ignored as you are reading into an integer array. Does your file actually contain a space character between each number?

Another approach would be to use readLn and have the required integers stored as new lines in the file, e.g.

1

2

3

Solution 2

I have tested the problem on Delphi 2009 console applications. Code like this

var
  F: Text;
  A: array[0..99] of Integer;
  I, J: Integer;

begin
  Assign(F, 'test.txt');
  Reset(F);
  I:= -1;
  while not EOF(F) do begin
    Inc(I);
    Read(F, A[I]);
  end;
  for J:= 0 to I do write(A[J], ' ');
  Close(F);
  writeln;
  readln;
end.

works exactly as you have written. It can be improved using SeekEOLN function that skips all whitespace characters; the next code does not produce wrong additional zero:

var
  F: Text;
  A: array[0..99] of Integer;
  I, J: Integer;

begin
  Assign(F, 'test.txt');
  Reset(F);
  I:= -1;
  while not EOF(F) do begin
    if not SeekEOLN(F) then begin
      Inc(I);
      Read(F, A[I]);
    end
    else Readln(F);
  end;
  for J:= 0 to I do write(A[J], ' ');
  Close(F);
  writeln;
  readln;
end.

Since all that staff is just a legacy in Delphi, I think it must work in Turbo Pascal.

Share:
13,093

Related videos on Youtube

user397232
Author by

user397232

Updated on June 04, 2022

Comments

  • user397232
    user397232 almost 2 years

    I'm using Pascal. I have a problem when dealing with reading file.

    I have a file with integer numbers. My pascal to read the file is:

    read(input, arr[i]);
    

    if my file content is 1 2 3 then it's good but if it is 1 2 3 or 1 2 3(enter here) (there is a space or empty line at the end) then my arr will be 1 2 3 0.

  • Marco van de Voort
    Marco van de Voort about 14 years
    +1 Very nice and classic solution. Classically it was only EOL or EOLN() or something not SEEKEOLN(). Don't know if that is a Delphi gotcha
  • Marco van de Voort
    Marco van de Voort about 14 years
    You need another variable (word typed in TP, longint typed in Delphi) that you pass to Val, where val stores its errors. Traditionally the name "code" is used for the var, probably because it was so in the TP help.

Related