我正在经历一个问题,虽然它很简单,但我看不到出路。如何正确地将文本文件中的值分配给C#中的2d矩阵#
我读一个文件,并将其分配给数组:
string[] lines = File.ReadAllLines(@"C:\Users\\Documents\Visual Studio 2017\Projects\TheMaze\TheMaze\Data\" + FileName + ".txt");
map = new MapFile();
int width = lines[0].Replace(" ", "").Length;
int height = lines.Length;
map.Matrix = new byte[width, height];
for (int y = 0; y < height; y++)
{
string line = lines[y].Replace(" ", "");
for (int x = 0; x < line.Length;x++)
{
//
}
Console.ReadKey();
}
}
return map;
}
我只是不明白如何从文件中正确分配值到我的矩阵对象。
要赋值给哪个变量?
我试过map.Matrix[x,y] = line[x]
但我得到一个错误,因为我必须将x转换为字节。
映射文件,我只有这个变量:public byte[,] Matrix = null;
如果我转换线[X]为字节所有的值都为35
以后打印我是那种完全丧失和欣赏任何帮帮我。
这仅仅是一个文本文件,我手动写道。
你不必转换''X ''转换为''byte'',但是''line [x]''的返回值。尝试下面的map.Matrix [x,y] = Convert.ToByte(line [x]);''如果你的文件在每一行都有一个数字,你必须写''map.Matrix [x,y ] = Convert.ToByte(int.Parse(line [x]));'' –
感谢您的答案。 我的文件实际上由'#','。','S','F'构成 其中#是墙壁,'。'是有效路径,'S'是起点,'F'是终点。 – Fix3r
你可以发表你的文件的样本,只需几行就足够了。 –