2016-03-21 26 views
0

因此,我必須編寫一個程序,從Values.txt文件中讀取值(數字)並將它們存儲到整數數組中(開始時我不知道數字在文件中的值,所以我不知道數組的長度)。 首先我遍歷該文件並使用計數器變量來獲取要存儲到數組中的值的數量。然後出現這個問題,我不知道如何從文件開始捕捉值並將它們存儲到數組中。 當我運行它時,我得到了0 0 0 0 0。如何重新啓動StreamReader以開始讀取文件的開頭

如果不是

myReader.DiscardBufferedData(); 
myReader.BaseStream.Seek(0, SeekOrigin.Begin); 
myReader.BaseStream.Position = 0; 

我使用myReader.Close()然後myReader = new StreamReader("Values.txt),結果是正確的,可有人請解釋爲什麼發生這種情況,並howcan我解決這個代碼:)

 string lineOfText = ""; 
     int counter = 0; 
     int[] intArray; 
     StreamReader myReader = new StreamReader("Values.txt"); 


     while(lineOfText != null) 
     { 
      lineOfText = myReader.ReadLine(); 
      if(lineOfText != null) 
      { 
       counter++; 
      } 
     } 
     intArray = new int[counter]; 

     myReader.DiscardBufferedData(); 
     myReader.BaseStream.Seek(0, SeekOrigin.Begin); 
     myReader.BaseStream.Position = 0; 

     counter = 0; 
     while(lineOfText != null) 
     { 
      lineOfText = myReader.ReadLine(); 
      if (lineOfText != null) 
      { 
       intArray[counter] = int.Parse(lineOfText); 
      } 
      counter++; 
     } 
     myReader.Close(); 

     for (int j = 0; j < intArray.Length; j++) 
     { 
      Console.WriteLine(intArray[j]); 
     } 
+1

_IF你can_,你可以通過簡單地調用這簡化了不少(https://msdn.microsoft.com/en-us/library ['File.ReadAllLines()'。] /s2tte0y1(v=vs.110).aspx) – CodingGorilla

回答

1

這解釋瞭如何在一次傳遞Return StreamReader to Beginning的情況下重置流。

您是否需要使用數組?列表對於你的工作是完美的,你可以稍後將列表推入數組中,或者直接從列表中進行工作。下面的代碼示例:

List<string> ints = new List<string>(); 
using (StreamReader sr = new StreamReader("example.txt")) 
{ 
    ints.Add(sr.ReadLine()); 
} 
+0

我必須使用一個數組:/ – Tandy

相關問題