[英]load txt file (m x n matrix) into 2d double array
I would like to load data from my txt file and store them in a 2D double array. 我想从txt文件加载数据并将其存储在2D双数组中。 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#.
我是C#的新手。 Can anyone suggest how to do this?
谁能建议该怎么做? Thank you.
谢谢。
EDIT: It throws NullReferenceException at the line: resultout[k][l] = double.Parse(col.Trim()); 编辑:它在行上抛出NullReferenceException:resultout [k] [l] = double.Parse(col.Trim());
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. 您初始化了一个由
double[]
类型的52个元素组成的数组,但是它们没有被初始化。 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
. 这只是意味着您尝试在
resultout[k]
为null
尝试获取不存在的数组的l
元素。 You have to initialize each row: 您必须初始化每一行:
resultout[k] = new double[number_of_elements];
where number_of_elements
you have to know before, for example: 您之前必须知道
number_of_elements
,例如:
var values = row.Trim().Split(' ');
resultout[k] = new double[values.Count()];
foreach (var col in values)
{
resultout[k][l] = double.Parse(col.Trim());
l++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.