通过读取分隔的文本文件填充结构变量数组

时间:2015-05-11 23:33:03

标签: arrays vb.net visual-studio-2012 streamreader member-variables

我有一个名为games.txt的文本文件,其中包含许多计算机游戏匹配的详细信息。每行代表:

Player1Score, Player1Name, Player1Age, Player 2Score, Player2Name, Player2Age 

以下是3行的示例(共有150行):

1, John, 32, 5, Albert, 54
3 Lisa, 33, 2, Michael, 36
4 Jessica, 24, 1 Robert, 32

我想将它们分配给一个结构数组,其中每个元素使用StreamReader有6个成员变量。这是结构变量:

Structure gameDetails
    Public Player1Score As Integer
    Public Player1Name As String
    Public Player1Age As Integer
    Public Player2Score As Integer
    Public Player2Name As String
    Public Player2Age As Integer
End Structure

我知道使用逗号作为分隔符,我可以将每个变量记录为数组中的不同元素:

Dim game() as String
game() = inFile.ReadLine.Split(","c)

会导致以这种方式分配每个元素:

game(0) = 1

game(1) = John

game(2) = 32

等。

有没有办法可以直接将所有成员变量分配给每个元素?也许每个逗号分隔成员变量,新行表示新元素?不幸的是,我不熟悉语法/命令,所以我不知道如何处理它。

请注意,我无法对任何内容进行硬编码,因为应用程序旨在从.txt中获取所有数据。

2 个答案:

答案 0 :(得分:0)

您是否可以尝试创建一个方法作为结构的一部分,如下所示:

public Sub MapLineEntry(targetLine() As String)
    Player1Score = CInt(targetLine(0))
    Player1Name = targetLine(1)
    Player1Age = CInt(targetLine(2))
    Player2Score = CInt(targetLine(3))
    Player2Name = targetLine(4)
    Player2Age = CInt(targetLine(5))
End Sub

您可能希望确保字符串数组具有正确数量的元素,但这将是一个开始。

答案 1 :(得分:0)

只是想说我找到了一种方法,虽然我不确定它有多高效。我最终将每行的每个部分(用逗号分隔)放到一个数组上。然后,我将数组分配给每个成员变量。然后我将它循环为每个变量执行它:

Dim inFile As System.IO.StreamReader
    inFile = New IO.StreamReader("Games.txt")
    If IO.File.Exists("Games.txt") Then

        Dim upperbound As Integer = Games.GetUpperBound(0)

        For i As Integer = 0 To upperbound
            'auxilary string
            Dim line(6) As String
            line = inFile.ReadLine.Split(","c)

            Games(i).Player1Score = CInt(line(0))
            Games(i).player1Name = line(1)
            Games(i).player1Age = CInt(line(2))
            Games(i).player2Score = CInt(line(3))
            Games(i).player2Name = line(4)
            Games(i).player2Age = CInt(line(5))
        Next i
    End If

谢谢你的帮助!

相关问题