pops
pops

Reputation: 45

Having trouble reading a double from a textfile with a formatexception

I'm trying to read the double for the construction of an object, yet I'm getting a format exception error and I don't know why. Here's the code for the main program:

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);
}

Then here's the text file:

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,

Upvotes: 0

Views: 81

Answers (2)

In your file's content you're missing a ',' between Webpage6 and 265.8 (hopefully its just a typo).

You can use this code:

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);
}

Upvotes: 0

Alexandru Popa
Alexandru Popa

Reputation: 166

The error is raised by the int.Parse conversion. The Readline() method reads a line of your file, that is the first line:

5.26,

The Split(',') will then generate you two elements in the data vector: "5.26" and the empty string. And when accessing the data[1] element, it will try to convert "" to int, which is not a valid input string. That is why you get that exception.

You will need to either read three lines consecutively, remove the comma and then do the conversions or keep the current logic, but modify the lines format on your file like this:

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

Upvotes: 1

Related Questions