Reading a list from txt file to array...

Please support our Pascal and Delphi advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Apr 2009
Posts: 7
Reputation: InS@NiTy is an unknown quantity at this point 
Solved Threads: 0
InS@NiTy InS@NiTy is offline Offline
Newbie Poster

Reading a list from txt file to array...

 
0
  #1
Apr 25th, 2009
Hello all, I'm pretty new to coding and I'm having a little trouble in reading a list to an array from a txt file.
What I'm trying to is write 24 words from a txt file to an array and then use a number to select one at random (It's for a very simple hangman style game)
I've tried writing a procedure to read in the words and then a function which returns the random word but I've tried a few things and looked online for tutorials and I cant find one which tells me how to read from txt file to an array (I know how to do the random number generation...I think)
Like I said I'm pretty new so I'm not entirely sure If I'm using arrays correctly.
Here is the code I've written to read from the txtfile into the array (it doesn't work obviously though, when I print array contents to screen to test it's just blank)

Pascal and Delphi Syntax (Toggle Plain Text)
  1. Procedure ReadToArray;
  2. Var
  3. PhraseFile : TextFile;
  4. FileName : String;
  5. Begin
  6. FileName := 'C:\Dev-Pas\MyPhrases.txt';
  7. AssignFile (PhraseFile, FileName);
  8. Reset (PhraseFile);
  9. While Not EoF do
  10. Begin
  11. Read(PhraseFile);
  12. For Index := 1 To 24
  13. Do Writeln(RandomPhraseArray[Index]); {This is where I'm stuck, I'm not sure what to put on this line.}
  14. End;
  15. Close (PhraseFile);
  16. End;

Thanks for any help
Last edited by InS@NiTy; Apr 25th, 2009 at 8:12 pm.
Reply With Quote Quick reply to this message  
Join Date: Apr 2009
Posts: 1
Reputation: cyber21 is an unknown quantity at this point 
Solved Threads: 1
cyber21 cyber21 is offline Offline
Newbie Poster

Re: Reading a list from txt file to array...

 
0
  #2
Apr 26th, 2009
Hi

I am a total nube when it comes to this im in exactly the same situation as u i can get it to work but only by copying some code from another guy in my class i dont really understand it....I noticed with urs though u have not declared ur Index as a local variable....i i dont know if tht will solve the problemo....Here u go his is working coding for 2 procedures i have no idea how it works though so if u figure it out let me know cheers

Pascal and Delphi Syntax (Toggle Plain Text)
  1. procedure LoadWords(FilePath : string);
  2. var
  3. WordFile : TextFile;
  4. Phrase : string;
  5. Length : integer;
  6. begin
  7. Length := 0;
  8. AssignFile (WordFile, FilePath);
  9. {$I-} Reset (WordFile); {$I+}
  10. if (IOResult <> 0) then
  11. WriteLn('Error loading ' + FilePath)
  12. else
  13. begin
  14. Randomize();
  15. while not EoF (WordFile) do
  16. begin
  17. Readln(WordFile, Phrase);
  18. Length := Length + 1;
  19. SetLength(PhraseDictionary, Length);
  20. PhraseDictionary[Length-1] := Phrase;
  21. end;
  22. CloseFile (WordFile);
  23. end;
  24. end;
  25.  
  26.  
  27. procedure RandomPhrase();
  28. begin
  29. if (length(PhraseDictionary) > 0) then
  30. NewPhraseEntered(PhraseDictionary[Random(Length(PhraseDictionary))])
  31. else
  32. WriteLn('No phrases loaded to pick from!');
  33. end;

the LoadWords procedure happens as soon as the programme is run

Hope this helps

Adam x
Reply With Quote Quick reply to this message  
Join Date: Apr 2009
Posts: 7
Reputation: InS@NiTy is an unknown quantity at this point 
Solved Threads: 0
InS@NiTy InS@NiTy is offline Offline
Newbie Poster

Re: Reading a list from txt file to array...

 
0
  #3
Apr 26th, 2009
I tried that but it gave me an error:
"Error: Incompatible type for arg no. 1: Got TRANDOMPHRASEARRAY, expected OPENSHORTSTRING"
But trandomphrasearray is set as string, so I'm kinda confused here.

I kind of understand the code but I'm not sure why he put in Randomize() in the loadwords procedure or why it's giving me an error...

To get the random word I used:

Pascal and Delphi Syntax (Toggle Plain Text)
  1. Function GetRandomPhrase : String;
  2. Var
  3. ArrayIndexNo : Integer;
  4. NewRandomPhrase : String;
  5. Begin
  6. Randomize;
  7. ArrayIndexNo := random(24) + 1;
  8. Write(ArrayIndexNo);
  9. NewRandomPhrase := RandomPhraseArray[ArrayIndexNo];
  10. GetRandomPhrase := NewRandomPhrase;
  11. End;
And it seems to work because if I take out the readtoarray procedure, start the program and get it to print out the random phrase it'll print out the random number followed by a blank line (because there's nothing in it )
It's actually getting stuff into the array that's confusing me...
Reply With Quote Quick reply to this message  
Join Date: Feb 2009
Posts: 468
Reputation: FlamingClaw will become famous soon enough FlamingClaw will become famous soon enough 
Solved Threads: 113
FlamingClaw's Avatar
FlamingClaw FlamingClaw is offline Offline
Posting Pro in Training

Re: Reading a list from txt file to array...

 
0
  #4
Apr 26th, 2009
I have an idea,what do you say?
tesed and working in Dev-Pascal 1.9.2
  1.  
  2. Program Solution01;
  3. {
  4. we create a new array type,every element will contain
  5. one string that max 20 char,and contains 10 items.
  6. }
  7. Type TArray=Array[0..9]Of String[20];
  8.  
  9. {I put the text file to the c:\,you can modify the file's path}
  10. Const FileName = 'C:\MyPhrases.txt';
  11.  
  12. {the variables}
  13. Var PhraseArray:TArray;{reading into it from a text file}
  14. TheWords:TArray; {reading from it to a text file}
  15. RandomWords:TArray;{this will store the random words}
  16. Counter:Byte; {will count the lines}
  17. i,j:Byte; {loop variable,index}
  18. PhraseFile:Text;{your text file's variable}
  19. h:String; {this will one line}
  20.  
  21.  
  22. { RandomNumbers Function:
  23. this function will generate random integer number
  24. between 1 and the added number(this will the counter var)}
  25. Function RandomNumbers(RN:Byte):Byte;
  26. Var k:Byte;
  27. Begin
  28. k:=Random(9)+1;
  29. RandomNumbers:=k;
  30. End;
  31.  
  32.  
  33. { FileRead Procedure:
  34. we direct leave out the 'assigning'
  35. cause the main program already did it when it's called
  36. It has 3 argument 1,One text file
  37.   2,One array
  38.   3,One counter variable
  39. }
  40. Procedure FileRead(Var FR:Text;Var FR1:TArray;Var FR2:Byte);
  41. Begin
  42. {$I-} {Input Output check off}
  43. Reset(FR); {open for reading}
  44. {$I+} {Input Output check on}
  45. If (IoResult = 0) Then Begin
  46. FR2:=0;
  47. While (EoF(FR)=False) Do Begin
  48. ReadLn(FR,h);
  49. {fill the array with row}
  50. FR1[FR2]:=h;
  51. {write the result to the screen}
  52. WriteLn(FR2:2,'. element: ',h);
  53. Inc(FR2); {increase the counter varriable}
  54. End;
  55. WriteLn;
  56. WriteLn('Trying to fill an other array with 4 random words');
  57. WriteLn;
  58. Randomize;
  59. For i:=0 To 3 Do Begin
  60. j:=RandomNumbers(Counter);{calling our function}
  61. RandomWords[i]:=PhraseArray[j];
  62. WriteLn(i:2,'. element: ',RandomWords[i]);
  63. End;
  64. End
  65. Else WriteLn('Error during file reset.');
  66. End;
  67.  
  68. Begin {main}
  69. {the 'C:MyPhrases.txt' consist of words as fallows}
  70. {cause we do not know your text file's contents,I'm just}
  71. {putting 10 words,one word one line}
  72. TheWords[0]:='apple';
  73. TheWords[1]:='peach';
  74. TheWords[2]:='time';
  75. TheWords[3]:='day';
  76. TheWords[4]:='sun';
  77. TheWords[5]:='pascal';
  78. TheWords[6]:='small';
  79. TheWords[7]:='great';
  80. TheWords[8]:='ship';
  81. TheWords[9]:='milk';
  82.  
  83. {we write these words to the text file}
  84. Assign(PhraseFile,FileName);{assigning it,this is enough for one session}
  85. {notify the user ...}
  86. WriteLn('Assigning ok.');
  87.  
  88. {create the file...}
  89. ReWrite(PhraseFile);{open for writing}
  90.  
  91. {write the above words to this file}
  92. For i:=0 To 9 Do Begin
  93. WriteLn(PhraseFile,TheWords[i]);
  94. End;
  95. WriteLn('Writing from array ok.');
  96.  
  97. WriteLn('Trying to write from text file to Array.');
  98. WriteLn('If you see the list then the process was success.');
  99. WriteLn;
  100. FileRead(PhraseFile,PhraseArray,Counter); {calling our procedure}
  101. WriteLn;
  102.  
  103. Close(PhraseFile);{closing the file in front of the end of main program}
  104. WriteLn('Press enter to quit...');
  105. ReadLn;
  106. End.{end of main}
  107.  
  108. {
  109. -=Created by FlamingClaw=-
  110. -=2009.04.26=-
  111. }
Last edited by FlamingClaw; Apr 26th, 2009 at 12:32 pm.
Be a good part of the community.Don't be ungrateful.
If you ask something on the forum and you got the right answer then mark as solved!
If my opinion helped to you a lot then sometimes give reputation point to me.
I'm just a pascal programmer from Hungary.
Farewell...
Reply With Quote Quick reply to this message  
Join Date: Feb 2009
Posts: 468
Reputation: FlamingClaw will become famous soon enough FlamingClaw will become famous soon enough 
Solved Threads: 113
FlamingClaw's Avatar
FlamingClaw FlamingClaw is offline Offline
Posting Pro in Training

Re: Reading a list from txt file to array...

 
0
  #5
Apr 26th, 2009
Originally Posted by cyber21 View Post
Randomize();
  1. Randomize;
Remark Randomize Procedure.
Initializes the built-in random number
generator with a random value (obtained from
the system clock).

Declaration:
procedure Randomize;

Target:
Windows, Real, Protected

Remarks:
If Range is not specified, the result is a
Real-type random number within the range 0 <=
X < 1. If Range is specified, it must be an
expression of type Word, and the result is a
Word-type random number within the range 0 <=
X < Range. If Range equals 0, a value of 0 is
returned.

The random number generator should be
initialized by making a call to Randomize, or
by assigning a value to RandSeed.
Be a good part of the community.Don't be ungrateful.
If you ask something on the forum and you got the right answer then mark as solved!
If my opinion helped to you a lot then sometimes give reputation point to me.
I'm just a pascal programmer from Hungary.
Farewell...
Reply With Quote Quick reply to this message  
Join Date: Feb 2009
Posts: 468
Reputation: FlamingClaw will become famous soon enough FlamingClaw will become famous soon enough 
Solved Threads: 113
FlamingClaw's Avatar
FlamingClaw FlamingClaw is offline Offline
Posting Pro in Training

Re: Reading a list from txt file to array...

 
0
  #6
Apr 26th, 2009
Originally Posted by FlamingClaw View Post
  1. { RandomNumbers Function:
  2. this function will generate random integer number
  3. between 1 and the added number(this will the counter var)}
  4. Function RandomNumbers(RN:Byte):Byte;
  5. Var k:Byte;
  6. Begin
  7. k:=Random(RN)+1;{fixed,sorry}
  8. RandomNumbers:=k;
  9. End;
My bad writing that I wrote 9 in the Random's argument,and we wait for the number of lines.....
Sorry for that,but fixed and working
Anyway working with 9 too,cause I know that there are just 10 line.But semantic error......
Last edited by FlamingClaw; Apr 26th, 2009 at 12:52 pm.
Be a good part of the community.Don't be ungrateful.
If you ask something on the forum and you got the right answer then mark as solved!
If my opinion helped to you a lot then sometimes give reputation point to me.
I'm just a pascal programmer from Hungary.
Farewell...
Reply With Quote Quick reply to this message  
Join Date: Feb 2009
Posts: 468
Reputation: FlamingClaw will become famous soon enough FlamingClaw will become famous soon enough 
Solved Threads: 113
FlamingClaw's Avatar
FlamingClaw FlamingClaw is offline Offline
Posting Pro in Training

Re: Reading a list from txt file to array...

 
0
  #7
Apr 26th, 2009
Fixed version!
  1.  
  2.  
  3. Program Solution01;
  4. {
  5. we create a new array type,every element will contain
  6. one string that max 20 char,and contains 10 items.
  7. }
  8. Type TArray=Array[0..9]Of String[20];
  9.  
  10. {I put the text file to the c:\,you can modify the file's path}
  11. Const FileName = 'C:\MyPhrases.txt';
  12.  
  13. {the variables}
  14. Var PhraseArray:TArray;{reading into it from a text file}
  15. TheWords:TArray; {reading from it to a text file}
  16. RandomWords:TArray;{this will store the random words}
  17. Counter:Integer; {will count the lines}
  18. i,j:Byte; {loop variable,index}
  19. PhraseFile:Text;{your text file's variable}
  20. h:String; {this will one line}
  21.  
  22.  
  23. { RandomNumbers Function:
  24. this function will generate random integer number
  25. between 1 and the added number(this will the counter var)}
  26. Function RandomNumbers(RN:Byte):Byte;
  27. Var k:Byte;
  28. Begin
  29. k:=Random(RN);
  30. RandomNumbers:=k;
  31. End;
  32.  
  33.  
  34. { FileRead Procedure:
  35. we direct leave out the 'assigning'
  36. cause the main program already did it when it's called
  37. It has 3 argument 1,One text file
  38.   2,One array
  39.   3,One counter variable
  40. }
  41. Procedure FileRead(Var FR:Text;Var FR1:TArray;Var FR2:Integer);
  42. Begin
  43. {$I-} {Input Output check off}
  44. Reset(FR); {open for reading}
  45. {$I+} {Input Output check on}
  46. If (IoResult = 0) Then Begin
  47. FR2:=0;
  48. While (EoF(FR)=False) Do Begin
  49. ReadLn(FR,h);
  50. {fill the array with row}
  51. FR1[FR2]:=h;
  52. {write the result to the screen}
  53. WriteLn(FR2:2,'. element: ',h);
  54. If(EoF(FR))Then Break;
  55. Inc(FR2); {increase the counter varriable}
  56. End;
  57. WriteLn('Trying to fill an other array with 4 random words');
  58. WriteLn;
  59. Randomize;
  60. For i:=0 To 3 Do Begin
  61. j:=RandomNumbers(Counter);
  62. RandomWords[i]:=PhraseArray[j];
  63. WriteLn(i:2,'. element: ',RandomWords[i]);
  64. End;
  65. End
  66. Else WriteLn('Error during file reset.');
  67. End;
  68.  
  69. Begin {main}
  70. {the 'C:\MyPhrases.txt' consist of words as fallows}
  71. {cause we do not know your text file's contents,I'm just}
  72. {putting 10 words,one word one line}
  73. TheWords[0]:='apple';
  74. TheWords[1]:='peach';
  75. TheWords[2]:='time';
  76. TheWords[3]:='day';
  77. TheWords[4]:='sun';
  78. TheWords[5]:='pascal';
  79. TheWords[6]:='small';
  80. TheWords[7]:='great';
  81. TheWords[8]:='ship';
  82. TheWords[9]:='milk';
  83.  
  84. {we write these words to the text file}
  85. Assign(PhraseFile,FileName);{assigning it,this is enogh one session}
  86. {notify the user ...}
  87. WriteLn('Assigning ok.');
  88.  
  89. {create the file...}
  90. ReWrite(PhraseFile);{open for writing}
  91.  
  92. {write the above words to this file}
  93. For i:=0 To 9 Do Begin
  94. WriteLn(PhraseFile,TheWords[i]);
  95. End;
  96. WriteLn('Writing from array ok.');
  97.  
  98. WriteLn('Trying to write from text file to Array.');
  99. WriteLn('If you see the list then the process was success.');
  100. WriteLn;
  101. FileRead(PhraseFile,PhraseArray,Counter); {calling our procedure}
  102. WriteLn;
  103.  
  104. Close(PhraseFile);{closing the file in front of the end of main program}
  105. WriteLn('Press enter to quit...');
  106. ReadLn;
  107. End.{end of main}
  108. {
  109. -=Created and Fixed by FlamingClaw=-
  110. -=2009.04.26=-
  111. }
Last edited by FlamingClaw; Apr 26th, 2009 at 1:29 pm.
Be a good part of the community.Don't be ungrateful.
If you ask something on the forum and you got the right answer then mark as solved!
If my opinion helped to you a lot then sometimes give reputation point to me.
I'm just a pascal programmer from Hungary.
Farewell...
Reply With Quote Quick reply to this message  
Join Date: Apr 2009
Posts: 7
Reputation: InS@NiTy is an unknown quantity at this point 
Solved Threads: 0
InS@NiTy InS@NiTy is offline Offline
Newbie Poster

Re: Reading a list from txt file to array...

 
0
  #8
Apr 26th, 2009
Thanks for the reply, that helped alot!
But there is one problem; I tried using your code but instead of writing to the txt file and then into the array I just tried reading straight from the txt file into the array, but it seems to delete everything in the txt file and the array comes out blank again, I've probably looked over something small, any idea what I did wrong?
Reply With Quote Quick reply to this message  
Join Date: Feb 2009
Posts: 468
Reputation: FlamingClaw will become famous soon enough FlamingClaw will become famous soon enough 
Solved Threads: 113
FlamingClaw's Avatar
FlamingClaw FlamingClaw is offline Offline
Posting Pro in Training

Re: Reading a list from txt file to array...

 
0
  #9
Apr 26th, 2009
First we need the text file and its contents
and then we need an arrray to read into the text file contents
one word one line
If you have your text file then
Of course your file can't be empty

  1. Procedure FileReadInToArray;
  2. Var data:array[1..10]of String;{your array}
  3. F:Text;
  4. FileName =String;
  5. Lines:String;
  6. Counter:Integer;
  7. Begin
  8. FileName:='C:\yourfile.txt';
  9. Assign(F,FileName);
  10. {$I-}
  11. Reset(F);
  12. {$I+}
  13. If (IoResult = 0) Then Begin
  14. Counter:=1;
  15. While Not(EoF(F)) Do Begin
  16. ReadLn(F,Lines);
  17. Data[Counter]:=Lines;
  18. If (EoF(F)) Then Break;
  19. Inc(Counter);{increase 'Counter' by 1}
  20. End; {of while}
  21. End
  22. Else WriteLn('Error when reading the file');
  23. Close(F);
  24. End;

there is another problem with it,the contents of 'Data' live only inside the procedure,and when the procedure ends its variables are finishes its works too.... and they disappears.....

  1.  
  2.  
  3. Program Solution01;
  4.  
  5. Uses Crt;
  6.  
  7. Var i:Byte;
  8.  
  9. Procedure FileReadInToArray;
  10. Var data:array[1..10]of String;{your array}
  11. F:Text;
  12. FileName :String;
  13. Lines:String;
  14. Counter:Integer;
  15. Begin
  16. FileName:='C:\yourfile.txt';
  17. Assign(F,FileName);
  18. {$I-}
  19. Reset(F);
  20. {$I+}
  21. If (IoResult = 0) Then Begin
  22. Counter:=1;
  23. While Not(EoF(F)) Do Begin
  24. ReadLn(F,Lines);
  25. Data[Counter]:=Lines;
  26. If (EoF(F)) Then Break;
  27. Inc(Counter);{increase 'Counter' by 1}
  28. End; {of while}
  29. End
  30. Else WriteLn('Error when reading the file');
  31. Close(F);
  32. End;
  33.  
  34. Begin {main}
  35. FileReadInToArray;
  36. For i:=1 To 10 Do WriteLn(Data[i]);
  37. ReadLn;
  38. End.{end of main}
When you run this program it will stop an error message
Local variable 'Data' assigning but not found....
Last edited by FlamingClaw; Apr 26th, 2009 at 2:26 pm.
Be a good part of the community.Don't be ungrateful.
If you ask something on the forum and you got the right answer then mark as solved!
If my opinion helped to you a lot then sometimes give reputation point to me.
I'm just a pascal programmer from Hungary.
Farewell...
Reply With Quote Quick reply to this message  
Join Date: Feb 2009
Posts: 468
Reputation: FlamingClaw will become famous soon enough FlamingClaw will become famous soon enough 
Solved Threads: 113
FlamingClaw's Avatar
FlamingClaw FlamingClaw is offline Offline
Posting Pro in Training

Re: Reading a list from txt file to array...

 
0
  #10
Apr 26th, 2009
But if we place the variables the right place then
  1.  
  2.  
  3. Program Solution01;
  4.  
  5. Uses Crt;
  6.  
  7. Var i:Byte;
  8. data:array[1..10]of String;{your array}
  9. F:Text;
  10. FileName:String;
  11. Lines:String;
  12. Counter:Integer;
  13.  
  14. Procedure FileReadInToArray;
  15. Begin
  16. FileName:='C:\yourfile.txt';
  17. Assign(F,FileName);
  18. {$I-}
  19. Reset(F);
  20. {$I+}
  21. If (IoResult = 0) Then Begin
  22. Counter:=1;
  23. While Not(EoF(F)) Do Begin
  24. ReadLn(F,Lines);
  25. Data[Counter]:=Lines;
  26. If (EoF(F)) Then Break;
  27. Inc(Counter);{increase 'Counter' by 1}
  28. End; {of while}
  29. End
  30. Else WriteLn('Error when reading the file');
  31. Close(F);
  32. End;
  33.  
  34. Begin {main}
  35. FileReadInToArray;
  36. For i:=1 To 10 Do WriteLn(Data[i]);
  37. ReadLn;
  38. End.{end of main}

Now it is working well ,got it now?
Be a good part of the community.Don't be ungrateful.
If you ask something on the forum and you got the right answer then mark as solved!
If my opinion helped to you a lot then sometimes give reputation point to me.
I'm just a pascal programmer from Hungary.
Farewell...
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



Tag cloud for Pascal and Delphi
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC