Reading an array from a text file

I have a problem. When the program reads a text file, it always get out of the line and crashed.

var f:text;
    i,j,cs:byte;
    a:array[0..10,0..10] of int64
begin
    assign(f,'anything.txt');
    reset(f);
    cs:=0;
    while eoln(f)=false do
    begin
        read(f,a[0,cs]);
        inc(cs);
    end;
    close(f);
end.

Here is the content of anything.txt: 2 4 8 16

exitcode=201

Upvotes: 1

Views: 541

Answers (1)

MartynA
MartynA

Reputation: 30715

You have not told us which compiler you are using.

In Delphi and Turbo Pascal which preceded it, run-time error 201 means "range check error". I don not still have Turbo Pascal installed but your program compiles and runs as a "console application" correctly in Delphi with only one minor change, namely to insert a semi-colon (';') after int64. It runs correctly whether the compiler has range-checking turned on or not.

It also runs correctly in FreePascal + Lazarus.

So, unless you are using a different compiler which also happens to have a run-time error code 201, your problem seems to be caused by something you have not included in your question. In any case you should learn to debug this kind of problem yourself. So:

Look up how to use use the debugger in your Pascal compiler. Place a breakpoint on the line inc(cs) e.g. by pressing F5and run the program. When it stops at the BP, place debug watches (using Ctrl-F5 in Delphi/TP) on the values of cs and a and observe the values carefully. Press F8 repeatedly to single step the program, and see if you can see where and why it goes wrong.

One possibility for what is causing your problem is that you are not reading the copy on anything.txt you think you are: because you don't include a path to the file in assign(f Windows will use the copy of anything.txt, if any, in whatever it thinks the current directory is. To avoid this, include the path to where the file is, as in

assign(f, 'C:\PascalData\Anything.Txt');

Also btw, you don't need to compare a boolean function (or expression) againt true or false as in

 while eoln(f)=false do

Instead you can simply do

 while not eoln(f) do

Upvotes: 2

Related Questions