Search code examples
c#monodevelop

Error Message when converting an array of strings from a text file to an array of doubles


I just have a quick (I think) question regarding a program I'm working on in C#. I have a text file with a long list of numbers, like this:

41.673993158 0.000000000 258.436256

41.673992499 -0.000001364 258.462068

41.673991841 -0.000002700 258.487880

And I need to create an array that contains each number separately as a double(or float). i.e.

Array[0] = 41.673993158

Array[1] = 0.000000000 ...etc.]

Right now, I have the numbers in an array, but they are all strings. I have the following code:

 string text = System.IO.File.ReadAllText("/Applications/Unity/Projects/Underwater/SampleFile.txt");
 if (text != null)
 {

     string[] strings = text.Split (' ');

     System.Console.WriteLine("Contents of SampleFile = ");
     for (int i = 0; i < strings.Length; i++) 
     {
         Console.WriteLine (strings[i]);
     }
  }

This code works perfect. It outputs each number on a separate line in the console, which leads me to believe that each number has it's own place in the array. However, they are all still strings, so when I try to convert them to doubles using this code:

double[] nums = new double[strings.Length];
for (int i = 0; i < strings.Length; i++)
{
    nums[i] = Convert.ToDouble(strings[i]);
}     

I get thrown an exception error, and can't figure out why. Here's the error message:

System.FormatException has been thrown.

Unknown Char

Details: double.Parse (s="258.436256\r\n41.673992499", provider={en-CA})

System.Convert.ToDouble (value="258.436256\r\n41.673992499")

I can't move on in my program until I have an array of doubles, so any help is greatly appreciated!


Solution

  • You can see from your exception message that it's trying to parse two numbers at once that are separated by a carriage return.

    You're splitting by space, but not by line. Writing this to the console would look correct, however.

    Change your split to include both space and CRLF:

    text.Split(new[] {" ", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);
    

    You could even combine with some LINQ to parse and then create the array - this is a far terser solution:

    var nums = text
        .Split(new[] {" ", "\r\n"}, StringSplitOptions.RemoveEmptyEntries)
        .Select(double.Parse)
        .ToArray();
    

    See this fiddle for a working demo.