0

I would like to load data from my txt file and store them in a 2D double array. I was trying something like this:

String input = File.ReadAllText(@"E:\c\vstup.txt");

int k = 0, l = 0;
double[][] resultout = new double[52][];
foreach (var row in input.Split('\n'))
{
    l = 0;
    foreach (var col in row.Trim().Split(' '))
    {
        resultout[k][l] = double.Parse(col.Trim());
        l++;
    }
    k++;
}

It is not working. I am new in C#. Can anyone suggest how to do this? Thank you.

EDIT: It throws NullReferenceException at the line: resultout[k][l] = double.Parse(col.Trim());

user2886091
  • 725
  • 7
  • 16
  • 29
  • What do you mean by _It is not working_ ? Any exception or error message? – Soner Gönül Feb 13 '14 at 07:24
  • The file have a fixed structure? The count of numbers in all lines are equal? – alexmac Feb 13 '14 at 07:24
  • 1. What is `input` in this line `foreach (var row in input.Split('\n'))`? 2. Instead of `input.Split('\n')` can you try `input.Split(System.Environment.NewLine)`. I am not sure it will work or not. But might be your text file uses `'\n\r'` for line break. 3. you can try reading line by line instead of splitting by `'\n'` – Iqbal Feb 13 '14 at 07:25

1 Answers1

0

You do not initialize each row. In line:

double[][] resultout = new double[52][];

you initialize an array of 52 elements of type double[], but they are not initialized. So when you are trying to:

resultout[k][l] = double.Parse(col.Trim());

it simply means you try to get l element of not existing array while resultout[k] is simply null. You have to initialize each row:

resultout[k] = new double[number_of_elements];

where number_of_elements you have to know before, for example:

var values = row.Trim().Split(' ');
resultout[k] = new double[values.Count()];
foreach (var col in values)
{
    resultout[k][l] = double.Parse(col.Trim());
    l++;
}
Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58