需要从文件到数组读取字符串

时间:2015-10-04 13:31:51

标签: pascal

我需要从文件中读取行。文件看起来像这样:

5
Juozas tumas     6 7 8 9 7
Andrius rapšys   2 9 8 7 1
petras balvonas  1 1 1 2 3 
Daiva petronyte  8 9 7 8 4
Julia bertulienė 10 10 10 5 1

当我尝试阅读时,我收到错误"重载"。

这是我的代码:

 WriteLn('Hi,press ENTER!');
  Assign(x,'D:/Duomenys.txt');
  reset(x);
  readln(x,k);

  for i := 0 to k do
  begin
      read(x,c[i],d[i]);
  end;

  close(x);
  Readln;

1 个答案:

答案 0 :(得分:0)

您需要手动解析字符串。否则输入将无效。分析并尝试此代码。

type
  TMyRec = record //each line of your text file contains alike set of data
    Name1, Name2: string;
    Numbers: array [1 .. 5] of word;
  end;

var
  x: text;
  tmps, s: string;
  SpacePos: word;
  RecArray: array of TMyRec;
  i: byte;

procedure DeleteSpacesAtBeginning(var str: string);
//code will delete spaces before the processed string
begin
  repeat
    if pos(' ', str) = 1 then //if the first char in string is ' '
      Delete(str, 1, 1);
  until pos(' ', str) <> 1;
end;

begin
  WriteLn('Hi,press ENTER!');
  Assign(x, 'd:\Duomenys.txt');
  reset(x);
  readln(x, s); // actually, you don't need any counter. Use eof instead;
  SetLength(RecArray, 0);//clear the dynamic array
  while not eof(x) do
  begin
    SetLength(RecArray, Length(RecArray) + 1);
    //append one empty record to the dynamic array
    readln(x, s);
    WriteLn(s); //if you really need it
    SpacePos := pos(' ', s); //finds the first space position
    RecArray[High(RecArray)].Name1 := Copy(s, 1, SpacePos - 1); 
    //copies substring from the string
    Delete(s, 1, SpacePos); //deletes the substring and space after it

    DeleteSpacesAtBeginning(s);
    SpacePos := pos(' ', s);
    RecArray[High(RecArray)].Name2 := Copy(s, 1, SpacePos - 1);
    //assignes the last name
    Delete(s, 1, SpacePos);

    for i := 1 to 4 do //4 because the 5th does not have space char after it
    //may be 5 if you have ' ' before the line break
    begin
      DeleteSpacesAtBeginning(s);
      SpacePos := pos(' ', s);
      tmps := Copy(s, 1, SpacePos - 1);
      RecArray[High(RecArray)].Numbers[i] := StrToInt(tmps);
      Delete(s, 1, SpacePos);
    end;
    DeleteSpacesAtBeginning(s); //now we assign the 5th number
    RecArray[High(RecArray)].Numbers[5] := StrToInt(s);

  end; //repeat the code until all the file si not read to the end
  sleep(1000);
  readln;
  //do anything you want with the processed data stored in the array
end.