tags:

views:

373

answers:

4

Hi guys,

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.

How to solve this? Thanks.

A: 

You could read the string into a temporary and then trim it prior to converting it.

It doesnt hurt to mention basics like what type of Pascal on what platform you're using in order that people can give a specific answer (as the article notes, there isnt a nice way OOTB in many Pascals)

Ruben Bartelink
A: 

If I recall there was a string function called Val that converts a string to a number...my knowledge of Pascal is a bit rusty (Turbo Pascal v6)

var
   num : integer;
   str : string;
begin
   str := '1234';
   Val(str, num); (* This is the line I am not sure of *)
end;

Hope this helps, Best regards, Tom.

tommieb75
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.
Marco van de Voort
+1  A: 

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

EddieCatflap
+1  A: 

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.

Serg
+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