I've been working all day trying to convert a string from a text file into a double array but can't figure out why I am getting the error "the file could not be read; input string was not in the correct format".
I currently have a application that reads back the contents of the text file in a string. I want it that when the string is converted into the double array I can then tell the console to print the double array and it will print the values of the text file that was in the string originally.
Here is my code:
double[] x = new double [3501];
This is where I define the double array. I do this first:
try
{
using (StreamReader sr = new StreamReader("test.txt"))
{
String line = sr.ReadToEnd();
string[] fields = line.Split(new char[] { ' ' });
x = new double [fields.Length];
for (int i = 0; i < fields.Length; i++)
{
x[i] = Convert.ToDouble(fields[i]);
Console.WriteLine(x[i]);
}
Line is the input string that contains a column full of numbers and is then split. I then tell it to print the contents of x[i] but thats when an exception is thrown:
catch (Exception e)
{
// Log the exception and quit...
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Can anyone figure what is wrong with my code and why it's not working?
Messagethat the exception is returning?input string was not in the correct format. Pretty much says it all; one of your input values could not be parsed by theConvert.ToDoublefunction.