【问题标题】:Populate an Array of Structure Variables by Reading a Delimited Text File通过读取分隔文本文件填充结构变量数组
【发布时间】:2015-05-11 23:33:03
【问题描述】:

我有一个名为 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

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

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 中获取所有数据。

【问题讨论】:

  • 只是评论一个错字,game.txt的示例行中缺少2个逗号。

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


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    只是想说我想出了一个方法,虽然我不确定它的效率如何。最后我把每一行的每一部分(用逗号分隔)放到一个数组中。然后,我将数组分配给每个成员变量。然后我循环它为每个变量做它:

    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
    

    感谢您的帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多