将矩阵写入文本文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将矩阵写入文本文件相关的知识,希望对你有一定的参考价值。

所以我已经完成了如何从第一行定义元素的文本文件中读取矩阵,但是我的问题是我将如何执行与写入文本文件相反的操作。我想要询问用户第0行0列,然后添加,并将此代码写入控制台,但不知道如何进入文本文件

这是写入控制台的代码:

Dim size As Integer = 3
Dim numberWidth As Integer = 2
Dim format As String = "D" & numberWidth

Dim A(size - 1, size - 1) As Integer
For i As Integer = 0 To A.GetUpperBound(0)
    For j As Integer = 0 To A.GetUpperBound(1)
        Console.Write(String.Format("Enter The Matrix Element at A[Row {0}, Col {1}]: ", i, j))
        A(i, j) = Convert.ToInt16(Console.ReadLine())
    Next
Next

这是用于读取矩阵的代码

Dim path = "d:matrix.txt"
Dim A(,) As Integer
Using reader As New IO.StreamReader(path)
    Dim size = reader.ReadLine() ' read first line which is the size of the matrix (assume the matrix is a square)
    Redim A(size - 1, size - 1)

    Dim j = 0 ' the current line in the matrix
    Dim line As String = reader.ReadLine() ' read next line
    Do While (line <> Nothing) ' loop as long as line is not empty
        Dim numbers = line.Split(" ") ' split the numbers in that line
        For i = 0 To numbers.Length - 1
            A(j, i) = numbers(i) ' copy the numbers into the matrix in current line
        Next

        j += 1 ' increment the current line
        line = reader.ReadLine() ' read next line
    Loop
End Using

Console.WriteLine("Matrix A :")
Dim numberWidth As Integer = 2
Dim format As String = "D" & numberWidth
For i As Integer = 0 To A.GetUpperBound(0)
    Console.Write("| ")
    For j As Integer = 0 To A.GetUpperBound(1)
        Console.Write("{0} ", A(i, j).ToString(format))
    Next
    Console.WriteLine("|")
Next

保存功能:

    Dim A(,) As Integer
Sub SaveMatrix()
    Dim path As String = "z:matrix.txt"







    Using fs As New System.IO.FileStream(path, IO.FileMode.OpenOrCreate)
        fs.SetLength(0) ' reset file length to 0 in case we are overwriting an existing file
        Using sw As New System.IO.StreamWriter(fs)
            Dim line As New System.Text.StringBuilder
            sw.WriteLine((A.GetUpperBound(0) + 1).ToString()) ' size of array in first line
            For i As Integer = 0 To A.GetUpperBound(0)
                line.Clear()
                For j As Integer = 0 To A.GetUpperBound(1)
                    line.Append(A(i, j).ToString() & " ")
                Next
                sw.WriteLine(line.ToString().Trim()) ' output each row to the file
            Next
        End Using
    End Using
    Console.WriteLine("")
    Console.WriteLine("Matrix successfully saved to:")
    Console.WriteLine(path)


End Sub
答案

这是一个基于演示如何输入,保存和加载矩阵的框架。您可以根据需要实施的其他操作向菜单添加其他选项:

Module Module1

    Public A(,) As Integer

    Public Sub Main()
        Dim response As String
        Dim quit As Boolean = False
        Do
            Console.WriteLine("")
            Console.WriteLine("--- Menu Options ---")
            Console.WriteLine("1) Enter a Matrix")
            Console.WriteLine("2) Display Matrix")
            Console.WriteLine("3) Save Matrix")
            Console.WriteLine("4) Load Matrix")
            Console.WriteLine("5) Quit")
            Console.Write("Menu choice: ")
            response = Console.ReadLine()
            Console.WriteLine("")
            Select Case response
                Case "1"
                    EnterMatrix()

                Case "2"
                    DisplayMatrix()

                Case "3"
                    SaveMatrix()

                Case "4"
                    LoadMatrix()

                Case "5"
                    quit = True

                Case Else
                    Console.WriteLine("")
                    Console.WriteLine("Invalid Menu Choice")

            End Select
        Loop While (Not quit)

        Console.Write("Press any key to dismiss the console...")
        Console.ReadKey()
    End Sub

    Public Sub EnterMatrix()
        Dim valid As Boolean
        Dim size, value As Integer
        Console.Write("Enter the Size of the Square Matrix: ")
        Dim response As String = Console.ReadLine()
        If Integer.TryParse(response, size) Then
            If size >= 2 Then
                Console.WriteLine("")
                ReDim A(size - 1, size - 1)
                For i As Integer = 0 To A.GetUpperBound(0)
                    Console.WriteLine("--- Row " & i & " ---")
                    For j As Integer = 0 To A.GetUpperBound(1)
                        valid = False
                        Do
                            Console.Write(String.Format("Enter The Matrix Element at A[Row {0}, Col {1}]: ", i, j))
                            response = Console.ReadLine()
                            If Integer.TryParse(response, value) Then
                                A(i, j) = value
                                valid = True
                            Else
                                Console.WriteLine("")
                                Console.WriteLine("Matrix Element must be a valid Integer!")
                                Console.WriteLine("")
                            End If
                        Loop While (Not valid)
                    Next
                    Console.WriteLine("")
                Next
            Else
                Console.WriteLine("")
                Console.WriteLine("Size must be greater than or equal to 2!")
            End If
        Else
            Console.WriteLine("")
            Console.WriteLine("Invalid Size")
        End If
    End Sub

    Public Sub DisplayMatrix()
        If Not IsNothing(A) AndAlso A.Length > 0 Then
            Dim maxLength As Integer = Integer.MinValue
            For i As Integer = 0 To A.GetUpperBound(0)
                For j As Integer = 0 To A.GetUpperBound(1)
                    maxLength = Math.Max(maxLength, A(i, j).ToString.Length)
                Next
            Next

            Console.WriteLine("Matrix Contents:")
            For i As Integer = 0 To A.GetUpperBound(0)
                Console.Write("| ")
                For j As Integer = 0 To A.GetUpperBound(1)
                    Console.Write("{0} ", A(i, j).ToString().PadLeft(maxLength, " "))
                Next
                Console.WriteLine("|")
            Next
        Else
            Console.WriteLine("The Matrix is empty!")
        End If
    End Sub

    Public Sub SaveMatrix()
        If Not IsNothing(A) AndAlso A.Length > 0 Then
            Console.Write("Enter the name of the File to Save To (example: `Matrix.txt`): ")
            Dim response As String = Console.ReadLine()
            Dim fullPathFileName As String = System.IO.Path.Combine(Environment.CurrentDirectory, response)
            Try
                If System.IO.File.Exists(fullPathFileName) Then
                    Console.WriteLine("")
                    Console.WriteLine("There is already a file at:")
                    Console.WriteLine(fullPathFileName)
                    Console.WriteLine("")
                    Console.Write("Would you like to overwrite it? Enter 'Y' or 'YES' to confirm: ")
                    response = Console.ReadLine.ToUpper
                    If response <> "Y" AndAlso response <> "YES" Then
                        Exit Sub
                    End If
                End If
                Using fs As New System.IO.FileStream(fullPathFileName, IO.FileMode.OpenOrCreate)
                    fs.SetLength(0) ' reset file length to 0 in case we are overwriting an existing file
                    Using sw As New System.IO.StreamWriter(fs)
                        Dim line As New System.Text.StringBuilder
                        sw.WriteLine((A.GetUpperBound(0) + 1).ToString()) ' size of array in first line
                        For i As Integer = 0 To A.GetUpperBound(0)
                            line.Clear()
                            For j As Integer = 0 To A.GetUpperBound(1)
                                line.Append(A(i, j).ToString() & " ")
                            Next
                            sw.WriteLine(line.ToString().Trim()) ' output each row to the file
                        Next
                    End Using
                End Using
                Console.WriteLine("")
                Console.WriteLine("Matrix successfully saved to:")
                Console.WriteLine(fullPathFileName)
            Catch ex As Exception
                Console.WriteLine("")
                Console.WriteLine("Error Saving Matrix!")
                Console.WriteLine("Error: " & ex.Message)
            End Try
        Else
            Console.WriteLine("The Matrix is empty!")
        End If
    End Sub

    Public Sub LoadMatrix()
        Console.Write("Enter the name of the File to Load From (example: `Matrix.txt`): ")
        Dim response As String = Console.ReadLine()
        Try
            Dim A2(,) As Integer

            Dim line As String
            Dim value As Integer
            Dim values() As String
            Dim arraySize As Integer
            Dim fullPathFileName As String = System.IO.Path.Combine(Environment.CurrentDirectory, response)
            Using sr As New System.IO.StreamReader(fullPathFileName)
                line = sr.ReadLine ' get matrix size and convert it to an int
                If Integer.TryParse(line, value) Then
                    arraySize = value
                    ReDim A2(arraySize - 1, arraySize - 1)
                    For row As Integer = 0 To arraySize - 1
                        values = sr.ReadLine().Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                        If values.Length = arraySize Then
                            For col As Integer = 0 To arraySize - 1
                                If Integer.TryParse(values(col).Trim, value) Then
                                    A2(row, col) = value
                                Else
                                    Console.WriteLine("")
                                    Console.WriteLine("Invalid Element in file!")
                                    Exit Sub
                                End If
                            Next
                        Else
                            Console.WriteLine("")
                            Console.WriteLine("Invalid Row Size in file!")
                            Exit Sub
                        End If
                    Next
                Else
                    Console.WriteLine("")
                    Console.WriteLine("Invalid Matrix Size in first line of file!")
 

以上是关于将矩阵写入文本文件的主要内容,如果未能解决你的问题,请参考以下文章

如何将treeview的内容写入文本文件

记录C#常用的代码片段

如何将这个 Objective-C 代码片段写入 Swift?

将稀疏矩阵转储到文件中

matlab中如何将多个矩阵保存到同一个矩阵中?

将文本写入.txt文件的通用代码?