为什么vb在文本文件中存储错误的数据

时间:2014-11-18 21:01:59

标签: vb.net

大家好我想把一些数据从一个数组写入一个文本文件,我很难做到这一点。我的代码吼叫

代码,我将数据创建并存储到studentArray

Const intMAX_SUBSCRIPT_STUDENT As Integer = 6 'max amount of students
Const intMAX_SUBSCRIPT_STUDENT_SCORES As Integer = 5 'max amount of scores

'Structure for student data
Public Structure StudentData
    Dim strStudentName As String 'to hold the student name
    Dim dblTestScoreArr() As Double ' Array to hold the test scores
    ' Dim dblAverage As Double 'to hold the average
End Structure



Dim StudentsArray(intMAX_SUBSCRIPT_STUDENT) As StudentData

'Stores the students names into array
Public Sub StudentNameData()
    StudentsArray(0).strStudentName = Exercise3.txtNameStudent1.Text
    StudentsArray(1).strStudentName = Exercise3.txtNameStudent2.Text
    StudentsArray(2).strStudentName = Exercise3.txtNameStudent3.Text
    StudentsArray(3).strStudentName = Exercise3.txtNameStudent4.Text
    StudentsArray(4).strStudentName = Exercise3.txtNameStudent5.Text
    StudentsArray(5).strStudentName = Exercise3.txtNameStudent6.Text
End Sub

我创建文件的方法

Sub SaveFile()
    Dim outputFile As StreamWriter 'Object variables
    Dim strFilename As String


    strFilename = InputBox("Enter the filename.")
    Try
        'Create Object the file 
        outputFile = File.CreateText(strFilename)
        For Each obj As StudentData In StudentsArray
            outputFile.WriteLine(obj)
        Next
        outputFile.Close()
    Catch ex As Exception

    End Try
End Sub

文件中存储的内容     Lab_9.StudentTestScoreModule + StudentData     Lab_9.StudentTestScoreModule + StudentData      Lab_9.StudentTestScoreModule + StudentData      Lab_9.StudentTestScoreModule + StudentData      Lab_9.StudentTestScoreModule + StudentData      Lab_9.StudentTestScoreModule + StudentData

1 个答案:

答案 0 :(得分:0)

有点背景:

首先,在创建数组时,作为参数传递的数字不是数组元素的总和,而是上限。所以,你的数组实际上有7个位置(从0到6)。

现在,StreamWriter.WriteLine收到string作为参数。当你传递的东西不是字符串时,它会尝试使用.ToString()方法转换它,每个类和结构都有(继承自全能的object类)。现在,.ToString()方法的默认行为是返回该变量类型的全名。但是,您可以覆盖它以指定要返回的内容。

所以,如果你添加你的结构

Public Overrides Function ToString() as string
    'Put here what you want to write on the file e.g. return "Hello World"
End Function

并运行原始代码,该文件将包含您在结构的ToString方法中返回的任何内容(在示例中,它将放置" Hello World" 6次,每次一个数组成员。)

至于你的第二种方法(带有StreamWriter的方法)两件事:文件是空白的,可能是因为你在for each循环之后从未刷过流或关闭了流;并且您遇到与outputFile.WriteLine(obj.dblTestScoreArr)的第一个代码相同的问题:您正在打印Array.ToString()函数的结果,它将是System.Array。您必须逐个打印数组中的一个值,或者所有这些值。