Reading text file data into Arrays. lazarus / 61-Beginners ---------------------------------------------------------------------- hymcode · 2021-01-21 14:11 Hello everyone, I have a text file with some random numbers on each line, and I'd like to be able to display them with a number beside and make them selectable. Shown below is currently what I have, but I'm not sure if this is the correct method and as it stands I am unable to select the value I want. Updated: 22/01/21 Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program fileArray; uses sysutils; var  tf : textfile;  lineTxt, optionStr : string;  textArray : Array [1..100] of QWord;  lineArray : Array [1..100] of QWord;  lineNum, lineText, error_stat, option : Integer; const  MYFILE = 'NUMBERS.TXT'; begin  lineNum := 0;  lineText := 0;  error_stat := 0;  writeln('Reading files into an array');   {$I-}  AssignFile(tf, MYFILE);  {$I+}  error_stat := IOResult;   if error_stat = 0 then  begin    writeln('File assign successful');     {$I-}    reset(tf);    {$I+}    error_stat := IOResult;     if error_stat = 0 then    begin      writeln('File reset successful');    while not eof (tf) do       try        begin          readln(tf, linetxt);           lineNum := lineNum + 1;           textArray[lineText] := StrToQWord(lineTxt);           writeln(lineArray[lineNum], '. ', textArray[lineNum]);        end;    except        on Exception : EConvertError do        begin          lineNum:=  lineNum - 1;        end;      end;       writeln('Select a number: ');      readln(optionStr);       {$I-}      readStr(optionStr, option);      {$I+}      error_stat := IOResult;     if error_stat = 0 then      begin        {need to select the number to get the corresponding line from text file}         if ((option < 1) or (option > lineNum))then         begin           writeln('below 1 or greater than ', lineNum);         end         else         begin         writeln('it works');           writeln(lineArray[option], '. ', textArray[option]);         end;            end      else      begin      writeln('Incorrect Input');      end;    end;     {$I-}    close(tf);    {$I+}    error_stat := IOResult;     if error_stat = 0 then    begin      writeln('File closed');    end    else      writeln('File cannot be closed');      end;  readln;end. Output: Code: Text  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Reading files into an arrayFile assign successfulFile reset successful1. 1232. 3453. 789Select a number:2it works2. 345File closed What I hope to achieve is being able to select a number which corresponds to the line position in the text file, while making sure that any invalid lines are skipped. I hope this makes sense and would really appreciate some advice. Update: 22/01/2021 I think I have got my intended output in order now. Just need to do some more testing. ---------------------------------------------------------------------- MarkMLl · 2021-01-21 14:21 Looks serviceable, but also note the existence of TryStrToQWord() and StrToQWordDef() etc. If you want to do more complex checking then looking at regular expressions might possibly be justified. MarkMLl ---------------------------------------------------------------------- hymcode · 2021-01-21 15:00 Quote from: MarkMLl on January 21, 2021, 03:21:29 pmLooks serviceable, but also note the existence of TryStrToQWord() and StrToQWordDef() etc. If you want to do more complex checking then looking at regular expressions might possibly be justified. MarkMLl Thanks for the feedback and for the suggestions regarding TryStrToQWord() and StrToQWordDef(). Would you happen to know how I will now be able to make my number options now selectable by the user? ---------------------------------------------------------------------- MarkMLl · 2021-01-21 15:04 Quote from: hymcode on January 21, 2021, 04:00:45 pmThanks for the feedback and for the suggestions regarding TryStrToQWord() and StrToQWordDef(). Would you happen to know how I will now be able to make my number options now selectable by the user? Yes, all you have to do is write code for it. MarkMLl ---------------------------------------------------------------------- ASerge · 2021-01-21 16:59 Quote from: MarkMLl on January 21, 2021, 03:21:29 pmLooks serviceable, but also note the existence of TryStrToQWord() and StrToQWordDef() etc. I wouldn't call it serviceable. The file is not closed, and the input outside the array boundary is not checked. It is better to immediately learn how to write correct programs. ---------------------------------------------------------------------- Bart · 2021-01-21 17:22 Why don't you read the entire file into a TStringList? No need to have 2 arrays for indexing. Bart ---------------------------------------------------------------------- MarkMLl · 2021-01-21 17:28 Cut him some slack, chaps, this is the beginner's area and I'm sure that he'll tidy things up as he accumulates experience :-) @ASerge: an example would be useful, even if it were purely an outline like Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i open(...try// Stuff herefinally  Close(...end;  @Bart: There's a distinct possibility that he doesn't know about it since he might be working from an old Turbo Pascal book or a generic Pascal example. OP: You /will/ tidy things up eventually, won't you? :-) MarkMLl ---------------------------------------------------------------------- hymcode · 2021-01-21 17:31 Quote from: Bart on January 21, 2021, 06:22:40 pmWhy don't you read the entire file into a TStringList? No need to have 2 arrays for indexing. Bart I am making a console program which I would also like to translate into a HP Pascal program, which to the best of my knowledge does not support TStringList ---------------------------------------------------------------------- hymcode · 2021-01-21 17:37 Quote from: ASerge on January 21, 2021, 05:59:28 pmQuote from: MarkMLl on January 21, 2021, 03:21:29 pmLooks serviceable, but also note the existence of TryStrToQWord() and StrToQWordDef() etc. I wouldn't call it serviceable. The file is not closed, and the input outside the array boundary is not checked. It is better to immediately learn how to write correct programs. Thank you for noting that I have not closed my file. I've made the changes for this. But I am unsure what you mean by: "the input outside the array boundary is not checked" ---------------------------------------------------------------------- ASerge · 2021-01-21 17:40 Quote from: hymcode on January 21, 2021, 06:37:18 pmThank you for noting that I have not closed my file. I've made the changes for this. But I am unsure what you mean by: "the input outside the array boundary is not checked" What happens when you read 101 lines of data? ---------------------------------------------------------------------- hymcode · 2021-01-21 17:53 Quote from: ASerge on January 21, 2021, 06:40:21 pmQuote from: hymcode on January 21, 2021, 06:37:18 pmThank you for noting that I have not closed my file. I've made the changes for this. But I am unsure what you mean by: "the input outside the array boundary is not checked" What happens when you read 101 lines of data? Oh, right I see, sorry I was being very slow there. Yes I haven't added any checks against data going outside the boundaries of my array. My current focus at the moment is trying to understand how I can select one of the numbers displayed on the screen, but thank you for pointing this out to me and I hope to address it at some point. ---------------------------------------------------------------------- Bart · 2021-01-21 17:56 If the line in question is not a number (conversion fails) then you decrement the LineNumber. From that point on the LineArray is out of sync with the actual line numbers in the text file (I think). Give the following numbers.txt: Code: [Select]1 2 3 foo bar 5 6 When you ask the user for a number and the user enters 4, what should be the response of your program? Bart ---------------------------------------------------------------------- Bart · 2021-01-21 18:13 Also the first time you do Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i textArray[lineText] := StrToQWord(lineTxt); LineText is zero, so instant runtime error. Oh, and having a variable LineTex and a variable LineTxt is rather confusing when inspecting the code... Bart ---------------------------------------------------------------------- Bart · 2021-01-21 18:21 Fixing the bug above you get (given the numvers.txt 2 posts above): Code: [Select]C:\Users\Bart\LazarusProjecten\bugs\forum\linearray>filearray Reading files into an array File assign successful File reset successful 1. 1 2. 2 3. 3 4. 6 Select a number: 1 LineArray: 1 TextArray: 1 File closed C:\Users\Bart\LazarusProjecten\bugs\forum\linearray>filearray Reading files into an array File assign successful File reset successful 1. 1 2. 2 3. 3 4. 6 Select a number: 2 LineArray: 2 TextArray: 2 File closed C:\Users\Bart\LazarusProjecten\bugs\forum\linearray>filearray Reading files into an array File assign successful File reset successful 1. 1 2. 2 3. 3 4. 6 Select a number: 3 LineArray: 3 TextArray: 3 File closed C:\Users\Bart\LazarusProjecten\bugs\forum\linearray>filearray Reading files into an array File assign successful File reset successful 1. 1 2. 2 3. 3 4. 6 Select a number: 6 LineArray: 0 TextArray: 6 File closed Does that output make sense to you? Bart ---------------------------------------------------------------------- Bart · 2021-01-21 21:27 Quote from: hymcode on January 21, 2021, 06:31:15 pmI am making a console program which I would also like to translate into a HP Pascal program, which to the best of my knowledge does not support TStringList Does it support ReadStr() (which is ISO Extended Pascal, according to the fpc docs)? The default conversion routines number<->string are Val() and Str(). If you use these, you don't need a try..except block. Quote from: hymcode on January 21, 2021, 03:11:18 pmWhat I hope to achieve is being able to select a number which corresponds to the line position in the text file, while making sure that any invalid lines are skipped. What exactly do you mean by that? Should it show the number on the X-th line in the text file? Should it show the X-th valid entry in the text file? Do invalid lines matter when yoy say "corrsponds to the line position in the text file"? There's to much ambiguity. Bart ---------------------------------------------------------------------- hymcode · 2021-01-22 09:12 Quote from: Bart on January 21, 2021, 06:56:11 pmIf the line in question is not a number (conversion fails) then you decrement the LineNumber. From that point on the LineArray is out of sync with the actual line numbers in the text file (I think). Give the following numbers.txt: Code: [Select]1 2 3 foo bar 5 6 When you ask the user for a number and the user enters 4, what should be the response of your program? Bart If the user enters 4 the response from the program should be 5. If a line is detected to have an invalid value, I'd like to omit this from being including in the array. For example: Code: [Select]1 2 3 foo (skipped) bar (skipped) 4 5 I hope that helps. ---------------------------------------------------------------------- Bart · 2021-01-22 21:47 But then, why the 2 arrays? If that is what you want, one will suffice. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program filearray;{$R+} var  tf : textfile;  LineText, optionStr : string;  Q: QWord;  lineArray : Array [1..100] of QWord;  lineNum, error_stat, option : Integer; const  MYFILE = 'NUMBERS.TXT'; begin  Assign(tf, MyFile);  {$I-}  Reset(tf);  error_stat := IOResult;  if error_stat <> 0 then  begin    writeln('Error: cannot open ',MyFile);    halt(error_stat);  end;  LineNum := 0;  while not Eof(tf) and (LineNum < 100) do  begin    Readln(tf, LineText);    Val(LineText, Q, error_stat);    if error_stat = 0 then    begin      Inc(LineNum);    LineArray[LineNum] := Q;    end  end;  repeat    repeat      write('Enter line number between 1 and ',LineNum,', or 0 to quit: ');      readln(OptionStr);      Val(OptionStr, Option, error_stat);      if error_stat <> 0 then        writeln(OptionStr,' is not a valid number')      else        if (Option < 0) or (Option > LineNum) then        writeln('Line number must be between 1 and ',LineNum,'.');    until (error_stat = 0) and (Option >= 0) and  (Option <= LineNum);     if Option <> 0 then       writeln(Option,': ',LineArray[Option]);  until Option = 0;end. And with my example numbers.txt: Code: [Select]Enter line number between 1 and 4, or 0 to quit: 1 1: 1 Enter line number between 1 and 4, or 0 to quit: 2 2: 2 Enter line number between 1 and 4, or 0 to quit: 3 3: 3 Enter line number between 1 and 4, or 0 to quit: 4 4: 6 Enter line number between 1 and 4, or 0 to quit: 5 Line number must be between 1 and 4. Enter line number between 1 and 4, or 0 to quit: -999 Line number must be between 1 and 4. Enter line number between 1 and 4, or 0 to quit: 0 No exceptions needed, less code, less variables. Bart ---------------------------------------------------------------------- ASerge · 2021-01-23 05:30 Quote from: Bart on January 22, 2021, 10:47:45 pmNo exceptions needed, less code, less variables. Bart, what about closing the file? If the user tries to run a second copy of the program during the dialog, the program will not be able to read the file. ---------------------------------------------------------------------- MarkMLl · 2021-01-23 09:35 Quote from: ASerge on January 23, 2021, 06:30:14 amBart, what about closing the file? If the user tries to run a second copy of the program during the dialog, the program will not be able to read the file. Operating-system specific, and OP's given no clue as to what he's using. OTOH it has already been pointed out to him, so he knows it's something to fix. MarkMLl ---------------------------------------------------------------------- egsuh · 2021-01-23 09:55 I think most basic codes would look like as following.  I'm just using the inherent functionality of read statement --- which does convert itself. There are issues of whether more than one figure are allowed in one line. If you want only one number in one line, you may use "readln(f, i);" instead of "read(f, i);"  I do not know how to write console I/O, so I used TEdit to enter index number, but you may use readln statement if you want console interface. (Also displaying in memo, and using ShowMessage as well).  Following codes will raise exceptions twice when run within Lazarus IDE (Press continue), but not when run as standalone .exe file. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i implementation {$R *.lfm} var   data: array of integer; { TForm1 } procedure TForm1.Button1Click(Sender: TObject);var   i :integer;   f: Textfile;begin   assignfile(f, 'd:\tests\data.txt');   reset(f);   while not eof(f) do begin      try        read (f, i);        data += [i];      except      end;   end;   closefile(f);   for i:= Low(data) to High(data)       do memo1.lines.add('%d. %d', [i+1, data[i]]);end; procedure TForm1.Button2Click(Sender: TObject);var   i, err: integer;begin   val(trim(edit1.text), i, err);   if err <> 0 then ShowMessage('Please enter number only')   else if (i > Length(Data)) then ShowMessage('Your index is out of rarnge')   else ShowMessage(IntToStr(Data[i-1]));end; end.  Content of data.txt file is as follows: Code: [Select]101 this 222  33333 44 555555 ---------------------------------------------------------------------- Bart · 2021-01-23 12:03 Quote from: ASerge on January 23, 2021, 06:30:14 amBart, what about closing the file? If the user tries to run a second copy of the program during the dialog, the program will not be able to read the file. Yep, forgot that. Also, each read from the file should be followed by checking IOResult. Bart ---------------------------------------------------------------------- Bart · 2021-01-23 12:14 Quote from: egsuh on January 23, 2021, 10:55:54 amI think most basic codes would look like as following. Using dynamic arrays is not the most basic way of doing things. TS states that even TStringList isn't know in his Pascal dialect, so better stick to things that are widely supported, even in old dialects. (IIRC then classes in Delphi were introduced before dynamic arrays.) Quote from: egsuh on January 23, 2021, 10:55:54 amThere are issues of whether more than one figure are allowed in one line. This was never specified, and the original code did not cater for that possibility, which lead me to the assumption there would ever only be one numer on each line. Also the "give me a line number and I tell you which number" in it's original wording doesn't use plural. Quote from: egsuh on January 23, 2021, 10:55:54 amI do not know how to write console I/O What about write, writeln, read, readln? If you omit the textfile parameter, they write to stdout and read from stdin. I would have thought that was rather basic? Bart ---------------------------------------------------------------------- Bart · 2021-01-23 12:19 Quote from: Bart on January 23, 2021, 01:03:29 pmQuote from: ASerge on January 23, 2021, 06:30:14 amBart, what about closing the file? If the user tries to run a second copy of the program during the dialog, the program will not be able to read the file. Yep, forgot that. Also, each read from the file should be followed by checking IOResult. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program filearray;{$R+} //uses sysutils; var  tf : textfile;  LineText, optionStr : string;  Q: QWord;  lineArray : Array [1..100] of QWord;  lineNum, error_stat, option : Integer; const  MYFILE = 'NUMBERS.TXT'; procedure IOCheck(Msg: String);var  Err: Word;begin  Err := IOResult;  if Err <> 0 then  begin    writeln(Msg);    halt(Err);  end;end; begin  Assign(tf, MyFile);  {$I-}  Reset(tf);  IOCheck('Unable to open '+MyFile);  LineNum := 0;  while not Eof(tf) and (LineNum < 100) do  begin    Readln(tf, LineText);    IOCheck('Error reading from '+MyFile);    Val(LineText, Q, error_stat);    if error_stat = 0 then    begin      Inc(LineNum);    LineArray[LineNum] := Q;    end  end;  Close(tf);  //Ignore IO error on closing file  InOutRes := 0;  repeat    repeat      write('Enter line number between 1 and ',LineNum,', or 0 to quit: ');      readln(OptionStr);      Val(OptionStr, Option, error_stat);      if error_stat <> 0 then        writeln(OptionStr,' is not a valid number')      else        if (Option < 0) or (Option > LineNum) then        writeln('Line number must be between 1 and ',LineNum,'.');    until (error_stat = 0) and (Option >= 0) and  (Option <= LineNum);     if Option <> 0 then       writeln(Option,': ',LineArray[Option]);  until Option = 0;end. Bart