2014-03-30 166 views
2

我在這裏有一些代碼,應該打開一個文本文件並解析它。C#For循環不遞增

它是由標籤解析,換行符

據我所看到的,它應該解析的數據存儲在2維陣列。

陣列[線,數據]

所以

  System.IO.FileInfo enemyFile = new System.IO.FileInfo("Data\\enemies.txt"); 
     System.IO.StreamReader enemies = enemyFile.OpenText(); 
     string line; 
     string[,] enemyInfo = new string[20,20]; // Array to store parsed text 

     while ((line = enemies.ReadLine()) != null) 
     { 
      string[] items = line.Split('\n'); 
      string[] newItems; 
      for (int i = 0; i < items.Length; i++) 
      { 
       Console.WriteLine(i); 
       newItems = items[i].Split('\t'); 
       for (int i2 = 0; i2 < newItems.Length; i2++) 
       { 
        enemyInfo[i, i2] = newItems[i2]; 
        //testArray.ListArray(newItems); 
        Console.WriteLine("[{0},{1}] = {2}", i, i2, enemyInfo[i, i2]); 
        Console.ReadLine(); 

       } 
       Console.WriteLine("-"); 

      } 

應該把第一解析數據從第一行到enemyInfo [0,0]和下一個解析數據從第一行到enemyInfo [0,1]等等。

在換行符中,它應該開始將數據存儲在enemyInfo [1,0]和enemyInfo [1,1]等等中。

  1. Enemies.txt

    Name of Race Race_ID Class_ID Sex_ID ToHit Evade Damage Strength Dexterity Constitution Intelligence Charisma Wisdom Experience Level 
    Goblin 0 0 2 0 1 -1 6 8 6 4 4 4 1 1 
    Kobold 1 0 2 1 1 0 8 8 8 6 4 4 3 2 
    

難道只是我,做錯了什麼?無論我嘗試什麼,它都不會在第一個for循環中增加我,因此它會將新行保存在數組的同一維中。

希望我提供了足夠的信息。

在此先感謝。

//羅尼·亨裏克森

編輯:

忘了補充輸出我得到的一個例子。

[0,0] = Name of race 
[0,1] = Race 
and so on up to [0,14] and then it does this: 
[0,0] = Goblin 
[0,1] = 0 
and so on, up to [0,14] and then it does the same with the next line (kobold). 
+2

調用'斯普利特(「\ n」)'上獲得一個字符串分割從ReadLine()中總是返回一個包含一個項目(字符串本身)的數組,因爲ReadLine()在它到達輸入中的'\ n'後立即停止。 – dasblinkenlight

回答

4

你的錯誤是在通過的ReadLine與\n讀取該行的分裂,你應該直接在此符合01​​

int i = 0; 
    while ((line = enemies.ReadLine()) != null) 
    { 
     string[] items = line.Split('\t'); 
     for (int i2 = 0; i2 < items.Length; i2++) 
     { 
      Console.WriteLine(i2); 
      enemyInfo[i, i2] = items[i2]; 
      Console.WriteLine("[{0},{1}] = {2}", i, i2, enemyInfo[i, i2]); 
      Console.ReadLine(); 
     } 
     i++; 
    } 
+0

謝謝!我在閱讀上面的dasblinkenlights評論之後也想到了,但是非常感謝! :) – Ronin