2017-04-11 41 views
0

我想從文件中讀取數組中的值。我從文件部分讀取數據,但無法將其存儲到數組中,因爲它給了我一個錯誤「Value can not be null」,因爲在循環之後,我的變量的值變爲null並且數組不能爲null。這是我的。我意識到,for循環可能不在正確的位置,所以任何幫助將它放在哪裏會很好。c#如何從文件中存儲數組的值

Program p = new Program(); 

     int MAX = 50; 

     int[] grades = new int[MAX]; 

     string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\"; 

     string path = environment + "grades.txt"; 

    StreamReader myFile = new StreamReader(path); 

     string input; 

     int count = 0; 

     do 
     { 
      input = myFile.ReadLine(); 
      if (input != null) 
      { 
       WriteLine(input); 
       count++; 
      } 
     } while (input != null); 

     for (int i = 0; i < count; i++) 
     { 
      grades[i] = int.Parse(input); 
     } 
+0

什麼是'成績' – pm100

+0

成績是我在其中存儲grades.txt文件中的值的數組 –

+0

您剛剛從while循環退出後啓動for循環。當輸入爲空時退出while循環的條件是真的 – Steve

回答

1

剛剛從while循環退出後啓動for循環。當輸入爲空時,從while循環退出的條件爲true。當然,這並不是Int.Parse所接受的。
相反,你可以使用一個迴路,也要考慮到你不想循環50次以上,否則你超過數組大小

int count = 0; 
while((input = myFile.ReadLine()) != null && count < 50) 
{ 
    WriteLine(input); 
    grades[count] = int.Parse(input); 
    count++; 
} 

但是你可以有一個更靈活的方式來處理你的輸入如果您使用List<int>而不是整數數組。這樣一來,你就不必檢查當前的行數在文件

List<int> grades = new List<int>(); 
while((input = myFile.ReadLine()) != null) 
    grades.Add(int.Parse(input)); 
+0

謝謝我欣賞它 –

0
Program p = new Program(); 
int MAX = 50; 
int[] grades = new int[MAX]; 
string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\"; 
string path = environment + "grades.txt"; 
using (StreamReader myFile = new StreamReader(path)) 
{ 
    string input; 
    int count = 0; 
    while((!myFile.EndOfStream) && (count < MAX)) 
    { 
     input = myFile.ReadLine(); 
     if (!String.IsNullOrWhiteSpace(input)) 
     { 
      WriteLine(input); 
      grades[count] = int.Parse(input); 
      count++; 
     } 
    } 
} 

你絕對應該使用在你的流對象的「使用」的格局。在爲你保留大部分代碼和風格的同時,擺脫for循環。您的問題是,在轉到下一行之前,您沒有使用輸入值。你只有原始代碼中的最後一個值。

如果我們想
+0

恕我直言 - waaaay太複雜了,史蒂夫的解決方案更容易挖掘 – pm100

1

得到真正凝聚

var grades = File.ReadAllLines(path).Select(l=>Int.Parse(l)).ToArray(); 
+0

'... Select(Int.Parse)'是6個字符短加''ReadLines(...)'保存另一個3. –

+0

@AlexeiLevenkov :-)。我總是忘記,如果lambda是一個簡單的函數調用,我不必指定它的參數 – pm100

0

利用Path.Combine()幫助你在串聯路徑。

string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); 
    String fullPath = Path.Combine(environment, "grades.txt"); 

    int[] grades = File.ReadAllLines(fullPath).Select(p => int.Parse(p)).ToArray<int>(); 
    Console.WriteLine(grades); 

enter image description here

參考https://www.dotnetperls.com/file-readalllines如何使用File.ReadAllLines()它非常方便。

我在這裏使用LINQ,這有時簡化了一些東西。儘管現在看起來有點嚇人。我們讀取所有行,然後通過選擇每一行並將其轉換爲整數,然後輸出整數數組並將其保存到grades來解析結果。