将文本文件中的字符串读入Pascal中的Array

问题描述 投票:1回答:2

[使用此程序,我试图读取文件并将其随机打印到控制台。我想知道是否必须为此使用数组。例如,我可以将字符串分配到数组中,然后从数组中随机打印。但是,我不确定该如何处理。另一个问题是,当前程序无法从文件中读取第一行。我有一个文本文件text.txt,其中包含

1. ABC
2. ABC
...
6. ABC

下面是我的代码。

type
  arr = record 
  end;

var
  x: text;
  s: string;
  SpacePos: word;
  myArray: array of arr;
  i: byte;

begin
  Assign(x, 'text.txt');
  reset(x);
  readln(x, s); 
  SetLength(myArray, 0);
  while not eof(x) do
  begin
    SetLength(myArray, Length(myArray) + 1);
    readln(x, s);
    WriteLn(s);
  end;
end.

请让我知道如何解决这个问题!

pascal freepascal
2个回答
0
投票

您在进入读取循环之前碰巧读取了一行。因此,这是您的程序,从开始到结束都没有多余的readln()。

begin
  Assign(x, 'text.txt');
  reset(x);
  SetLength(myArray, 0);
  while not eof(x) do
  begin
    SetLength(myArray, Length(myArray) + 1);
    readln(x, s);
    WriteLn(s);
  end;
end.

0
投票

还有另一个问题是,我当前的程序无法从文件中读取第一行。

是的。但是您不要将其写入控制台。参见第三行,readln(x, s);

我正在尝试读取文件并将其随机打印到控制台。我想知道是否必须为此使用数组。

是的,这是一种合理的方法。

不是使用记录的数组,而是声明:

myArray : array of string.

要从数组中获取随机值,请使用Randomize初始化随机生成器,并使用Random()获取随机索引。

var
  x: text;
  myArray: array of String;
  ix: Integer;
begin
  Randomize;  // Initiate the random generator
  Assign(x, 'text.txt');
  reset(x);
  ix := 0; 
  SetLength(myArray, 0);
  while not eof(x) do
  begin
    SetLength(myArray, Length(myArray) + 1);
    readln(x, myArray[ix]);
    WriteLn(myArray[ix]);
    ix := ix + 1;
  end;
  WriteLn('Random line:');
  WriteLn(myArray[Random(ix)]);  // Random(ix) returns a random number 0..ix-1
end.
© www.soinside.com 2019 - 2024. All rights reserved.