2014-03-30 169 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