Results 1 to 4 of 4

Thread: How do I read an array from a text file?

  1. #1
    anuj76
    Guest

    How do I read an array from a text file?

    Hi,

    I am new to VB and it took me a whole half hour to figure out that you don't append every line with a semicolon!!

    I have a 71 by 71 integer matrix that is tab delimited stored in a text file. I want to read this into a 71 by 71 integer array. Could some please tell me how to go about it?

    I tried using a Variant, and the Split method and casting the result by Int(), but got Type Mismatches over and over again.

    Thank you in advance.
    Anuj

  2. #2
    -= B u g S l a y e r =- peet's Avatar
    Join Date
    Aug 2000
    Posts
    9,629
    hmm... arrays, yet another thing I don't do well...

    I'll stick my neck out anyway.. (BeachBum will be all over me after this )

    VB Code:
    1. Option Explicit
    2. Private Const NumRows = 70
    3. Private Const NumCols = 70
    4.  
    5. Private Sub Command1_Click()
    6.     Dim sArr() As String
    7.     Dim sTmp() As String
    8.     Dim i As Integer
    9.     Dim x As Integer
    10.     Dim iArr(NumRows, NumCols) As String
    11.     Dim sFileName As String
    12.    
    13.     sFileName = "C:\matrix.txt"
    14.    
    15.     Open sFileName For Input As #1
    16.         sArr = Split(Input(LOF(1), 1), vbCrLf)
    17.     Close #1
    18.    
    19.     For i = 0 To UBound(sArr())
    20.         sTmp = Split(sArr(i), vbTab)
    21.         For x = 0 To NumCols
    22.             iArr(i, x) = Int(sTmp(x))
    23.         Next x
    24.     Next i
    25. End Sub

    does what u want
    -= a peet post =-

  3. #3
    Frenzied Member macai's Avatar
    Join Date
    Jul 2001
    Location
    Napanoch NY
    Posts
    1,228
    Hmm peet, you forgot to explain to him about the concept of
    delimiters! ^^

    If you don't already know, a delimiter is like something in between
    2 substrings. For instance in this case, peet used a tab as
    the delimiter. So for instance the delimiter would be used like this

    "ArrayEntry0 ArrayEntry1"

    Then you could literally take whats in this string and "split" it into
    an array.
    VB Code:
    1. Dim MyArray() As String
    2. MyArray = Split("ArrayEntry0    ArrayEntry1", vbTab) 'This splits them by the delimiter
    3. MsgBox MyArray(0) 'Notice how this returns "ArrayEntry0"
    4. MsgBox MyArray(1) 'Notice how this returns "ArrayEntry1"
    Just making sure the dude understands what you were talking about peet.
    Hope this helps, laterz.
    Luke

  4. #4
    -= B u g S l a y e r =- peet's Avatar
    Join Date
    Aug 2000
    Posts
    9,629

    Thumbs up

    -= a peet post =-

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width