views:

32

answers:

1

I have a text file like

11111
10001
10001
11111

I need to read this into a 2d array of integers I already have the code to read the file

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

But i dont know what to do after that. I'm know this is something simple but i just cant think of it now -_-

+2  A: 

I assume the 2d array is to store each individual digit in each individual row. Also assume we only have 4 lines of 5 numbers each. (Don't assume this, unless you know its forceable--otherwise calculate the necessary size and redim the array)

    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
pinkfloydx33
Thanks this worked flawlessly. I did know the size of array ahead of time so no need to do the redim.
giodamelio
note that my catch statement merely skips setting the value in that array for that position. You should probably do something more robust such as exiting or forcing that index's value to -1 to indicate an error when you loop through it later
pinkfloydx33