从文本文件中读取矩阵,文本文件的第一行具有矩阵的尺寸,下一行将包含由行隔开的元素。我当时正在考虑使用此功能,但不知道如何从文本文件获取数据。
Dim path = "z:matrix.txt"
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)
Dim A(size - 1, size - 1) As Integer
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
Console.WriteLine(line)
Loop
End Using
3
1 3 5
2 4 6
7 8 9
答案 0 :(得分:1)
Dim path = "D:\matrix.txt"
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)
Dim A(size - 1, size - 1) As Integer
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
A.Dump() ' print the matrix in LinqPad
End Using
文本文件示例:
3
1 3 5
2 4 6
7 8 9
没有LinqPad的修改代码:
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