Reading integers in Pascal

I am using Pascal. I have a problem working with a read file.

I have a file with integers. My pascal to read the file:

read(input, arr[i]); 

if the contents of my file are 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 .

+4
source share
4 answers

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

Another approach would be to use readLn and have the required integers stored as readLn in the file, for example.

one

2

3

+1
source

I 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 the same as you wrote. It can be improved with the SeekEOLN function, which skips all whitespace characters; The following code does not cause an incorrect extra 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 these employees are just a legacy at Delphi, I think he should work at Turbo Pascal.

+1
source

You can read the string into a temporary one and then trim before converting it.

It’s worth mentioning the basics, like the type of Pascal on which platform you use, so that people can give a specific answer (as the article notes, there is no good way to OOTB in many Pascals)

0
source

If I remember, there was a string function called Val that converts the string to a number ... my knowledge of Pascal is a little 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, Regards, Tom.

0
source

Source: https://habr.com/ru/post/1299787/


All Articles