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)

Procedure ReadToArray;
Var
PhraseFile : TextFile;
FileName : String;
Begin
FileName := 'C:\Dev-Pas\MyPhrases.txt';
AssignFile (PhraseFile, FileName);
Reset (PhraseFile);
While Not EoF do
      Begin
           Read(PhraseFile);
           For Index := 1 To 24
           Do Writeln(RandomPhraseArray[Index]); {This is where I'm stuck, I'm not sure what to put on this line.}
      End;
Close (PhraseFile);
End;

Thanks for any help :)

Recommended Answers

All 12 Replies

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

procedure LoadWords(FilePath : string);
  var
    WordFile : TextFile;
    Phrase : string;
    Length : integer;
  begin
    Length := 0;
    AssignFile (WordFile, FilePath);
    {$I-} Reset (WordFile); {$I+}
    if (IOResult <> 0) then
        WriteLn('Error loading ' + FilePath)
    else
      begin
        Randomize();
        while not EoF (WordFile) do
          begin
            Readln(WordFile, Phrase);
            Length := Length + 1;
            SetLength(PhraseDictionary, Length);
            PhraseDictionary[Length-1] := Phrase;
          end;
      CloseFile (WordFile);
    end;
  end;


procedure RandomPhrase();
begin
  if (length(PhraseDictionary) > 0) then
    NewPhraseEntered(PhraseDictionary[Random(Length(PhraseDictionary))])
  else
    WriteLn('No phrases loaded to pick from!');
end;

the LoadWords procedure happens as soon as the programme is run

Hope this helps

Adam x

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. :S

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:

Function GetRandomPhrase : String;
Var
ArrayIndexNo : Integer;
NewRandomPhrase : String;
Begin
Randomize;
ArrayIndexNo := random(24) + 1;
Write(ArrayIndexNo);
NewRandomPhrase := RandomPhraseArray[ArrayIndexNo];
GetRandomPhrase := NewRandomPhrase;
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 :P)
It's actually getting stuff into the array that's confusing me...

I have an idea,what do you say?
tesed and working in Dev-Pascal 1.9.2

Program Solution01;
{
we create a new array type,every element will contain
one string that max 20 char,and contains 10 items.
}
Type TArray=Array[0..9]Of String[20];

{I put the text file to the c:\,you can modify the file's path}
Const FileName = 'C:\MyPhrases.txt';

{the variables}
Var PhraseArray:TArray;{reading into it from a text file}
    TheWords:TArray;   {reading from it to a text file}
    RandomWords:TArray;{this will store the random words}
    Counter:Byte;  {will count the lines}
    i,j:Byte;     {loop variable,index}
    PhraseFile:Text;{your text file's variable}
    h:String; {this will one line}


{ RandomNumbers Function:
this function will generate random integer number
between 1 and the added number(this will the counter var)}
Function RandomNumbers(RN:Byte):Byte;
Var k:Byte;
Begin
   k:=Random(9)+1;
   RandomNumbers:=k;
End;


{ FileRead Procedure:
we direct leave out the 'assigning'
cause the main program already did it when it's called
It has 3 argument 1,One text file
                  2,One array
                  3,One counter variable
}
Procedure FileRead(Var FR:Text;Var FR1:TArray;Var FR2:Byte);
Begin
   {$I-}       {Input Output check off}
   Reset(FR); {open for reading}
   {$I+}       {Input Output check on}
   If (IoResult = 0) Then Begin
      FR2:=0;
      While (EoF(FR)=False) Do Begin
         ReadLn(FR,h);
         {fill the array with row}
         FR1[FR2]:=h;
         {write the result to the screen}
         WriteLn(FR2:2,'. element: ',h);
         Inc(FR2); {increase the counter varriable}
      End;
      WriteLn;
      WriteLn('Trying to fill an other array with 4 random words');
      WriteLn;
      Randomize;
      For i:=0 To 3 Do Begin
        j:=RandomNumbers(Counter);{calling our function}
        RandomWords[i]:=PhraseArray[j];
        WriteLn(i:2,'. element: ',RandomWords[i]);
      End;
   End
   Else WriteLn('Error during file reset.');
End;

Begin {main}
   {the 'C:MyPhrases.txt' consist of words as fallows}
   {cause we do not know your text file's contents,I'm just}
   {putting 10 words,one word one line}
   TheWords[0]:='apple';
   TheWords[1]:='peach';
   TheWords[2]:='time';
   TheWords[3]:='day';
   TheWords[4]:='sun';
   TheWords[5]:='pascal';
   TheWords[6]:='small';
   TheWords[7]:='great';
   TheWords[8]:='ship';
   TheWords[9]:='milk';

   {we write these words to the text file}
   Assign(PhraseFile,FileName);{assigning it,this is enough for one session}
   {notify the user ...}
   WriteLn('Assigning ok.');

   {create the file...}
   ReWrite(PhraseFile);{open for writing}

   {write the above words to this file}
   For i:=0 To 9 Do Begin
     WriteLn(PhraseFile,TheWords[i]);
   End;
   WriteLn('Writing from array ok.');

   WriteLn('Trying to write from text file to Array.');
   WriteLn('If you see the list then the process was success.');
   WriteLn;
   FileRead(PhraseFile,PhraseArray,Counter); {calling our procedure}
   WriteLn;

   Close(PhraseFile);{closing the file in front of the end of main program}
   WriteLn('Press enter to quit...');
   ReadLn;
End.{end of main}

{
-=Created by FlamingClaw=-
-=2009.04.26=-
}

Randomize();

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.

{ RandomNumbers Function:
this function will generate random integer number
between 1 and the added number(this will the counter var)}
Function RandomNumbers(RN:Byte):Byte;
Var k:Byte;
Begin
   k:=Random(RN)+1;{fixed,sorry} 
   RandomNumbers:=k;
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...... :D

Fixed version!

Program Solution01;
{
we create a new array type,every element will contain
one string that max 20 char,and contains 10 items.
}
Type TArray=Array[0..9]Of String[20];

{I put the text file to the c:\,you can modify the file's path}
Const FileName = 'C:\MyPhrases.txt';

{the variables}
Var PhraseArray:TArray;{reading into it from a text file}
    TheWords:TArray;   {reading from it to a text file}
    RandomWords:TArray;{this will store the random words}
    Counter:Integer;  {will count the lines}
    i,j:Byte;     {loop variable,index}
    PhraseFile:Text;{your text file's variable}
    h:String; {this will one line}


{ RandomNumbers Function:
this function will generate random integer number
between 1 and the added number(this will the counter var)}
Function RandomNumbers(RN:Byte):Byte;
Var k:Byte;
Begin
   k:=Random(RN);
   RandomNumbers:=k;
End;


{ FileRead Procedure:
we direct leave out the 'assigning'
cause the main program already did it when it's called
It has 3 argument 1,One text file
                  2,One array
                  3,One counter variable
}
Procedure FileRead(Var FR:Text;Var FR1:TArray;Var FR2:Integer);
Begin
   {$I-}       {Input Output check off}
   Reset(FR); {open for reading}
   {$I+}       {Input Output check on}
   If (IoResult = 0) Then Begin
      FR2:=0;
      While (EoF(FR)=False) Do Begin
         ReadLn(FR,h);
         {fill the array with row}
         FR1[FR2]:=h;
         {write the result to the screen}
         WriteLn(FR2:2,'. element: ',h);
         If(EoF(FR))Then Break;
         Inc(FR2); {increase the counter varriable}
      End;
      WriteLn('Trying to fill an other array with 4 random words');
      WriteLn;
      Randomize;
      For i:=0 To 3 Do Begin
        j:=RandomNumbers(Counter);
        RandomWords[i]:=PhraseArray[j];
        WriteLn(i:2,'. element: ',RandomWords[i]);
      End;
   End
   Else WriteLn('Error during file reset.');
End;

Begin {main}
   {the 'C:\MyPhrases.txt' consist of words as fallows}
   {cause we do not know your text file's contents,I'm just}
   {putting 10 words,one word one line}
   TheWords[0]:='apple';
   TheWords[1]:='peach';
   TheWords[2]:='time';
   TheWords[3]:='day';
   TheWords[4]:='sun';
   TheWords[5]:='pascal';
   TheWords[6]:='small';
   TheWords[7]:='great';
   TheWords[8]:='ship';
   TheWords[9]:='milk';

   {we write these words to the text file}
   Assign(PhraseFile,FileName);{assigning it,this is enogh one session}
   {notify the user ...}
   WriteLn('Assigning ok.');

   {create the file...}
   ReWrite(PhraseFile);{open for writing}

   {write the above words to this file}
   For i:=0 To 9 Do Begin
     WriteLn(PhraseFile,TheWords[i]);
   End;
   WriteLn('Writing from array ok.');

   WriteLn('Trying to write from text file to Array.');
   WriteLn('If you see the list then the process was success.');
   WriteLn;
   FileRead(PhraseFile,PhraseArray,Counter); {calling our procedure}
   WriteLn;

   Close(PhraseFile);{closing the file in front of the end of main program}
   WriteLn('Press enter to quit...');
   ReadLn;
End.{end of main}
{
-=Created and Fixed by FlamingClaw=-
-=2009.04.26=-
}

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?

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

Procedure FileReadInToArray;
Var data:array[1..10]of String;{your array}
      F:Text;
      FileName =String;
      Lines:String;
      Counter:Integer;
Begin
FileName:='C:\yourfile.txt';
Assign(F,FileName);
{$I-}
Reset(F);
{$I+}
If (IoResult = 0) Then Begin
   Counter:=1;
   While Not(EoF(F)) Do Begin
      ReadLn(F,Lines);
      Data[Counter]:=Lines;
      If (EoF(F)) Then Break;
      Inc(Counter);{increase 'Counter' by 1}
   End; {of while}
End
Else WriteLn('Error when reading the file');
Close(F);
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.....

Program Solution01;

Uses Crt;

Var i:Byte;

Procedure FileReadInToArray;
Var   data:array[1..10]of String;{your array}
      F:Text;
      FileName :String;
      Lines:String;
      Counter:Integer;
Begin
FileName:='C:\yourfile.txt';
Assign(F,FileName);
{$I-}
Reset(F);
{$I+}
If (IoResult = 0) Then Begin
   Counter:=1;
   While Not(EoF(F)) Do Begin
      ReadLn(F,Lines);
      Data[Counter]:=Lines;
      If (EoF(F)) Then Break;
      Inc(Counter);{increase 'Counter' by 1}
   End; {of while}
End
Else WriteLn('Error when reading the file');
Close(F);
End;

Begin {main}
    FileReadInToArray;
    For i:=1 To 10 Do WriteLn(Data[i]);
   ReadLn;
End.{end of main}

When you run this program it will stop an error message
Local variable 'Data' assigning but not found....

But if we place the variables the right place then

Program Solution01;

Uses Crt;

Var i:Byte;
    data:array[1..10]of String;{your array}
    F:Text;
    FileName:String;
    Lines:String;
    Counter:Integer;

Procedure FileReadInToArray;
Begin
FileName:='C:\yourfile.txt';
Assign(F,FileName);
{$I-}
Reset(F);
{$I+}
If (IoResult = 0) Then Begin
   Counter:=1;
   While Not(EoF(F)) Do Begin
      ReadLn(F,Lines);
      Data[Counter]:=Lines;
      If (EoF(F)) Then Break;
      Inc(Counter);{increase 'Counter' by 1}
   End; {of while}
End
Else WriteLn('Error when reading the file');
Close(F);
End;

Begin {main}
    FileReadInToArray;
    For i:=1 To 10 Do WriteLn(Data[i]);
   ReadLn;
End.{end of main}

Now it is working well :D ,got it now?

Aha, got it working, thanks alot! :)

I think im doing this exam! For AS computing. :) Im trying to get past this problem. Im pretty confused!

Yeah it confused me too, this helped alot though, I can post the code I'm using if you want?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.