Hi All,
I am getting the message "input string was not in a correct format" about the line " numline = Convert.ToDouble(num);"
The program is supposed to read a csv and convert the fifth line of the file to an double array. The line to be read in looks like (and keeps going with 20 more numbers in that form):
"22.925507, 0.0000000, 0.0000000, "

I'm new to C# and this seemingly simple task has taken surprisingly long! Thanks in advance :)

Liam


ArrayList mtext = new ArrayList(); //declare array list for all data to be stored in as strings
            string textline; //each line of text, one at a time.
            int i = 0; //counter for which value in textline
            double[] numline = new double[25]; //double equivalent of textline
            string[] textlinesplit = new string[25]; //after textline is split into seperate numbers
            using (StreamReader m_reader = new StreamReader(@"C:\Users\Andreas\Documents\out5.csv")) //initialize file
            {
                while ((textline = m_reader.ReadLine()) != null) //read until end of file
                {

                    if (textline.Length == 0) //if end of file, leave loop
                        continue;
                    if (mtext.Count == 3) //if we're on the 5th line of numbers, convert line to double array
                    {
                        textlinesplit = textline.Split(',');
                        i = 0;
                        foreach (string num in textlinesplit)
                        {
                            if (num != null)
                            {
                                numline[i] = Convert.ToDouble(num);
                            }
                            i++;
                        }
                    }
                    mtext.Add(textline); // insert line at end of list
                }
            }

Problem is that in your string ("22.925507, 0.0000000, 0.0000000, "), the Split has created a last item equal to a " " (space char), which the Convert.ToDouble(" ") yields the exception.

To correct, remove the trailing (last) comma.

As an alternative, change line 20 (or similar check for spaces) to be:

if (num != null && num.Trim().Length > 0)

You might also want to put your index increment for numline ("i++") to be inside the if block so it only gets incremented when your num is actually put into the numline array:

if (num != null && num.Trim().Length > 0)
                    {
                        numline[i] = Convert.ToDouble(num);
                        i++;
                    }

Edited 7 Years Ago by DdoubleD: n/a

Thank you! Thank you! Thank you!

I have been programming in MATLAB for years and I think it's high degree of tolerance has given me some bad habits!

Cheers
Liam

This question has already been answered. Start a new discussion instead.