Sean
Sean

Reputation: 1

Converting textfile to a two dimensional array (with a comma deliminator) VB.NET

I'm trying like crazy to figure out how to do this. I need to look at a textfile that I've designed (for a quiz program)- line by line (the line having two parts separated by a comma) for the question (First part) and the boolean answer (second part). Ie. A line from the text file will look like:

You have 10 fingers,true
you have 10 toes,true
you have 2 thumbs,true

I just need to be able to convert this to an array whereby I can access the elements on command, so for instance (0,0) would display the first question in a textbox, and I would reference the users answer (in the form of true or false) against (0,1) where I would use a counter to count the number of correct answers. After the user answers the first question I could loop to the second question to be displayed in the array and so forth. Although there may be more advanced ways of doing this I will need to use a stream reader in this context.

I see I can read ONE line into an array with :

dim line() as string = io.file.readalllines("C:\data.txt")
dim value(2) as integer
value = line.split(","c)

but I need to access each line, with their answers, one at a time. If I could get the textfile into an two dimensional array I could simply access each element on command. Help :)

Any help would be GREATLY appreciated!

Upvotes: 0

Views: 1141

Answers (1)

Steve
Steve

Reputation: 216293

I suggest to use a proper class to handle your data. For example you could write a class named QA that stores the Question text and the boolean value of the answer

Public Class QA
    Public Question as String
    Public Answer as Boolean
End Class

You could read your file with File.ReadLines or use the StreamReader class.

Sub Main

    ' A list of QA objects loaded from file
    Dim qaList as New List(Of QA)()

    Using sw = new StreamReader("C:\data.txt")
        Dim line as String
        Do
            line = sw.ReadLine()
            If line Is Nothing Then Exit Do
            Dim  parts() = line.Split(","c)

            ' Initialize a new QA object and add it to the list
            qaList.Add(new QA() _
            With 
            { 
                 .Question = parts(0), 
                 .Answer = Convert.ToBoolean(parts(1)) 
            })
        Loop
    End Using

Now you could use the List(Of QA) as an array referencing the elements using an indexer

    Console.WriteLine(qaList(0).Question)
    Console.WriteLine(qaList(0).Answer)

End Sub

Upvotes: 1

Related Questions