2015-10-04 60 views
-1

我需要從文件讀取行。文件看起來像這樣:需要從文件讀取字符串到數組

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; 
+0

爲了得到良好的答覆,這裏有幾件事要牢記。 1)假設你需要自己編寫所有的代碼。我們通常只會指出你正確的方向。 2)你試過了什麼? (Google那句話)。我們需要看到你解決這個問題的嘗試。 3)確保你已經徹底檢查過文檔和搜索引擎。如果其他人以這種方式找到了答案,你會得到一個簡略的「RTD」或「LMGTFY」以及大量的downvotes。 – CodeMouse92

回答

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.