无法使用formatexception从文本文件中读取double

时间:2018-04-06 13:50:08

标签: c# double streamreader formatexception

我试图阅读double来构建对象,但我收到格式异常错误,我不知道为什么。 这是主程序的代码:

ArrayList Webpages = new ArrayList();
String FileName = "Medium.txt";
StreamReader newSR = new StreamReader(FileName);
while (!newSR.EndOfStream)
{
    string[] data = (newSR.ReadLine()).Split(',');
    Webpage newEntry = new Webpage(Double.Parse(data[0]), int.Parse(data[1]), data[2]);
    Webpages.Add(newEntry);
}

然后是文本文件:

5.26,
46,
WebPage1,
7.44,
76,
WebPage2,
8.35,
42,
WebPage3,
46.2,
9,
WebPage4,
12.44,
124,
WebPage5,
312.88,
99,
WebPage6
265.8,
984,
WebPage7,

2 个答案:

答案 0 :(得分:1)

int.Parse转换引发错误。 Readline()方法读取文件的一行,即第一行:

  

5.26,

Split(',')将在数据向量中生成两个元素:“5.26”和空字符串。当访问data [1]元素时,它会尝试将“”转换为int,这不是有效的输入字符串。这就是你得到那个例外的原因。

您需要连续读取三行,删除逗号,然后进行转换或保留当前逻辑,但修改文件中的行格式,如下所示:

5.26,46,WebPage1
7.44,76,WebPage2
8.35,42,WebPage3

答案 1 :(得分:0)

在你的文件内容中,你错过了网页6和265.8之间的','(希望它只是一个错字)。

您可以使用此代码:

System.Collections.ArrayList Webpages = new System.Collections.ArrayList();
string fileName = "Medium.txt";
string fileContent = "";
using (System.IO.StreamReader sr = new System.IO.StreamReader(fileName))
{
    /* loads all the file into a string */
    fileContent = sr.ReadToEnd();
}
/* split the file's contents, StringSplitOptions.RemoveEmptyEntries will remove the last empty element (the one after Webpage7,) */
string[] data = fileContent.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
/* packs of 3 (1st the double, 2nd the int and 3rd the string) */
for (int i = 0; i < data.Length; i += 3)
{
    /* double parse with CultureInfo.InvariantCulture as per Hans Passant comment */
    Webpage newEntry = new Webpage(
        double.Parse(data[i], System.Globalization.CultureInfo.InvariantCulture),
        int.Parse(data[i + 1]),
        data[i + 2].Trim());
    Webpages.Add(newEntry);
}