【问题标题】:“Input string was not in a correct format” while parsing the content of a file解析文件内容时出现“输入字符串格式不正确”
【发布时间】:2020-12-20 08:14:34
【问题描述】:

我需要帮助,我不知道为什么我的输入文件 strArr(1) 中的数量数组出现错误,提示输入字符串的格式不正确。

Dim objReader As IO.StreamReader
Dim objWriter As New IO.StreamWriter("C:\Users\user\Desktop\StationeryFolder\output.txt")
Dim strLine As String
Dim strName As String
Dim intQuantity As Integer
Dim intTotal As Integer
Dim strArr() As String

If IO.File.Exists("C:\Users\user\Desktop\StationeryFolder\input.txt") = True Then
    objReader = IO.File.OpenText("C:\Users\user\Desktop\StationeryFolder\input.txt")
Else
    MsgBox("File is not exist")
    Close()
End If

Do While objReader.Peek <> -1
    strLine = objReader.ReadLine()
    strArr = strLine.Split("  ")
    strName = strArr(0)
    intQuantity = Convert.ToInt32(strArr(1)) //this is where the error occurs
    intTotal = intTotal + intQuantity
    lstDisplay.Items.Add(strName & "    " & intQuantity.ToString())
    objWriter.WriteLine(strName & "     " & intQuantity.ToString())
Loop

lstDisplay.Items.Add("Total Quantity of Stationeries are: " & intTotal.ToString())
objWriter.WriteLine("Total Quantity of Stationeries are: " & intTotal.ToString())
objReader.Close()
objWriter.Close()

输入文件内部:

Markers   
15
Pens     
25 

【问题讨论】:

  • 您发布的示例中每行是否有一个项目?在那种情况下,你在分裂什么?在几乎相同的问题中查看方法shown here
  • 如果您在同一行中同时有描述和 a 值,请发布反映真实内容的示例,以及有关格式的一些详细信息:如果描述可以包含多个单词,则例子。
  • 有点混乱,您正在使用 ReadLine ,然后拆分该行,但在您的示例中,每行只有一个项目......您想要的第二个对象在第二行。你可以尝试不拆分看看结果。
  • 我之前已经更正过这段代码。您要删除问题吗?
  • 您的strArr = strLine.Split(" ") 正在向Split 方法发送一个包含2 个字符的字符串。由于没有Split 的重载只需要String,我只能假设它正在将其转换为Char 数组。如果你有 Option Strict On,它总是应该是,这甚至不会编译。您的文件中的行似乎没有任何空格,那么结果数组中怎么可能有 2 个元素?

标签: vb.net


【解决方案1】:

我使用 .net File 类而不是流。 ReadAllLine 返回文件中行的数组。我使用了StringBuilder,它与字符串不同,它是可变的(可变的)。避免创建和丢弃多个字符串的代码。我在引号前使用了由$ 指示的插值字符串。这允许将变量直接插入用大括号括起来的字符串中。

Private Sub OPCode()
    Dim inputPath = "C:\Users\user\Desktop\StationeryFolder\input.txt"

    If Not IO.File.Exists(inputPath) Then
        MsgBox("File does not exist")
        Close()
    End If

    Dim lines = File.ReadAllLines(inputPath)
    Dim total As Integer
    Dim sb As New StringBuilder
    For i = 0 To lines.Length - 2 Step 2
        lstDisplay.Items.Add($"{lines(i)}    {lines(i + 1)}")
        sb.AppendLine($"{lines(i)}    {lines(i + 1)}")
        total += CInt(lines(i + 1))
    Next

    lstDisplay.Items.Add($"Total Quantity of Stationeries are: {total}")
    sb.AppendLine($"Total Quantity of Stationeries are: {total}")

    File.WriteAllText("C:\Users\user\Desktop\StationeryFolder\output.txt", sb.ToString)
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    相关资源
    最近更新 更多