我创建了一个文本文件,其间有空白。所以我不知道如何读入文件并添加数字。它应该基本上添加数字并给出总数。我真的被卡住了。我认为你需要创建一个循环和另一个变量,但我不知道在哪里添加它。 提前致谢: 进口System.IO 模块模块1
Sub Main()
Dim objStreamReader As StreamReader
Dim strLine As String
Dim filename As String
Console.WriteLine("This program will add up all the numbers in this program.")
Console.WriteLine("Please type in the name of the file to view.")
filename = Console.ReadLine()
'Pass the file path and the file name to the StreamReader constructor.
objStreamReader = New StreamReader("C:\Users\Oliver\Documents\Computing\" + filename + ".txt")
'Read the first line of text.
strLine = objStreamReader.ReadLine
'Continue to read until you reach the end of the file.
Do While Not strLine Is Nothing
'Write the line to the Console window.
Console.WriteLine(strLine)
'Read the next line.
strLine = objStreamReader.ReadLine
Loop
objStreamReader.Close()
Console.Read()
End Sub
结束模块
答案 0 :(得分:0)
不确定您的文件中包含哪种数字,但您可以尝试这样做。此外,不是先读取一行然后循环,而是循环读取行并保持运行总计:
Dim objStreamReader As StreamReader
Dim strLine As String
Dim filename As String
Dim total as Integer
Console.WriteLine("This program will add up all the numbers in this program.")
Console.WriteLine("Please type in the name of the file to view.")
filename = Console.ReadLine()
'Pass the file path and the file name to the StreamReader constructor.
objStreamReader = New StreamReader("C:\Users\Oliver\Documents\Computing\" + filename + ".txt")
Do While Not objStreamReader.EndOfStream
'Read line.
strLine = objStreamReader.ReadLine
'Write the line to the Console window.
Console.WriteLine(strLine)
'If the line has data, add its value to total
if strLine.Trim.length > 0 then
total += CInt(strLine.Trim)
end if
Loop
objStreamReader.Close()
Console.WriteLine("Total: " & total)
Console.Read()