2014-03-13 68 views
1

我一直在使用這個鏈接作爲一個例子,但一直有它的煩惱: 2d Array from text file c#文本保存到陣列

我有一個包含一個文本文件:

1 1 0 0 
1 1 1 0 
0 0 0 1 
0 1 0 0 

我試圖使用的功能:

static void Training_Pattern_Coords() 
{ 
    String input = File.ReadAllText(@"C:\Left.txt"); 

    int i = 0, j = 0; 
    int[,] result = new int[4, 4]; 
    foreach (var row in input.Split('\n')) 
    { 
     j = 0; 
     foreach (var col in row.Trim().Split(' ')) 
     { 
      result[i, j] = int.Parse(col.Trim()); 
      j++; 
     } 
     i++;  
    } 
    Console.WriteLine(result[1, 3]); 

    Console.ReadLine(); 
} 

但是我一直在該行收到錯誤消息(輸入字符串的格式不正確):

foreach (var row in input.Split('\n')) 

我認爲它與文本文件中的空格有關,但我不完全確定。謝謝你的幫助!

+0

對不起,該文本文件是一個4x4陣列與它們之間的空格,但它已成爲問題中的一行: – user3365114

+0

http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ – Samuel

+0

這些行最有可能被'\ r \ n'分隔(回車/換行)。 –

回答

2

而不是File.ReadAllText使用File.ReadLines。通過這樣做,你將不需要使用Split('\n')

int[,] result = new int[4, 4]; 

var lines = File.ReadLines(@"C:\Left.txt") 
       .Select(x => x.Split()).ToList(); 
for (int i = 0; i < 4; i++) 
{ 
    for (int j = 0; j < 4; j++) 
    { 
     result[i, j] = int.Parse(lines[i][j]); 
    } 
} 
+1

爲了降低內存開銷,他應該在ReadAllLines上使用ReadLines,因爲他只是對它進行foreach 。 – Servy

0

更換任何\r(回車)

input = input.Replace('\r',' '); 
0

更換你\ r爲 「\ r \ n」 個

試試這個:

foreach (var row in input.Split("\r\n"))