2010-10-31 105 views
0

我有一个像转换文本文件转换成二维数组在vb.net

11111 
10001 
10001 
11111 

一个文本文件,我需要读入整数 的二维数组,这个我已经有代码读取文件

Dim fullpath = "Path to File" 
Dim objReader As StreamReader 
objReader = New StreamReader(fullpath) 

但我不知道该做什么之后。 我知道这是简单的东西,但我现在不能想起它-_-

+0

你Google一下吗? [StreamReader](http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx)Class(System.IO) – frayser 2010-10-31 02:51:50

回答

2

我假设2d数组是存储每个单独的行中的每个单独的数字。还假设我们只有4行5个数字。 (不要以为这个,除非你知道它的forceable - 否则,计算所需的规模和REDIM阵列)

Dim myArray(4, 5) As Integer, y As Integer = 0, x As Integer = 0 
    Dim fullpath = "Path to File" 

    Using sr As StreamReader = New StreamReader(fullpath) 
      Do While sr.Peek() >= 0 
        For Each c As Char In sr.ReadLine 
         Try 
          myArray(x, y) = Integer.Parse(c) 
         Catch ex As Exception 'i assume this is the only possible error, but we could be out of bounds due to assuming the actual size of the file/line... catch specific exceptions as necessary' 
          Console.WriteLine(String.Format("Error converting {0} to an integer.", c)) 
         End Try 
         y += 1 
        Next 
        x += 1 
        y = 0 
      Loop 
     End Using 
+0

谢谢,这工作完美无瑕。我确实知道阵列的大小,所以不需要做redim。 – giodamelio 2010-10-31 03:41:33

+0

请注意,我的catch语句只是跳过为那个位置设置数组的值。你应该做一些更强大的事情,例如退出或强制该索引的值为-1,以便在稍后循环时指出错误 – pinkfloydx33 2010-10-31 03:44:00