2011-03-12 116 views
1

我正在寫一個自定義的結構處理程序,我有以下幾種類型:帕斯卡爾 - 神祕的領域增加

type 
StrLen = 0..MaxLen; 
Str = ^StrInst; 

StrInst = record 
length: StrLen; 
data: array [StrPos] of char; 
end; 

然後我有以下程序:

procedure ReadStr(var S: Str); 
var pos: StrLen; 
begin 
     S^.length:=0; 
     pos := 0; 
     writeln('pos before entering:',pos); 
     writeln; 
     with S^ do begin 
     repeat 
       Inc(pos); 
       Read(data[pos]); 
     until (ord(data[pos]) = 13) or (pos > MaxLen+1); 
     writeln('pos after entering:',pos); 
     length := pos-1; 
     end; 
end; 

問題是,當我讀入該類型的第二個對象時,pos變量,從而長度字段,正在得到一個神祕的增加1.下面的代碼

ReadStr(S1); 
ReadStr(S2); 

輸出(在這兩種情況下,當我輸入 '123'):

pos before entering:0 
123 
pos after entering:4 

pos before entering:0 
123 
pos after entering:5 

會很gladful,如果有人清除的情況對我來說。先謝謝你。

回答

1

你錯過了一些可能相關的程序部分。特別是,如果這是在Windows上(取決於你如何閱讀文件),你可能在第二個字符串中有一個額外的字符,因爲你停在一個CR而不處理下面的LF。

+0

那麼,我不讀任何文件,輸入讀入結構的字段。 – Arnthor 2011-03-12 09:44:29

+0

@Nordvind - 然而,你正在閱讀的價值,這似乎是最合理的解釋。測試很簡單,將'13'換成'10',然後看看。順便說一句,你跳過第一個元素,你想切換'Inc'和'Read'的位置。 – 2011-03-12 11:13:31

+0

@Sertac Akyuz:我也認爲'Read'應該放在'Inc'之前,但是後來我看到該數組被定義爲char'的data:array [StrPos],並且不知道'StrPos'是否標識以0開頭的索引範圍,雖然OP有可能錯誤地將其替換爲「StrLen」,它以0開始。 – 2011-03-12 12:37:38