从c#中的.txt文件中读取x,y值

本文关键字:读取 中的 txt 文件 | 更新日期: 2023-09-27 18:13:22

我正试图从文本文件中读取x和y值到字符串数组中,其中该行在','上被分割然而,当我运行这段代码时,我得到一个错误,说索引超出了数组的第一个元素的边界。我试过使用临时字符串来存储数据,然后转换它们,但我仍然在第二个元素上得到相同的错误。这是我的代码,我已经实现没有临时字符串。

string line;
while ((line = coordStream.ReadLine()) != null)
{
   string[] temp = new string[2];
   temp[0] = "";
   temp[1] = "";
   temp = line.Split(',');
   trees[count].X = Convert.ToInt16(temp[0]);
   trees[count].Y = Convert.ToInt16(temp[1]);
   count++;
 }

下面是临时存储的代码:

string line;
while ((line = coordStream.ReadLine()) != null)
{
   string[] temp = new string[2];
   temp[0] = "";
   temp[1] = "";
   temp = line.Split(',');
   string xCoord = temp[0];
   string yCoord = temp[1];
   trees[count].X = Convert.ToInt16(xCoord);
   trees[count].Y = Convert.ToInt16(yCoord);
   count++;
 }

我知道这似乎是一个微不足道的错误,但我似乎不能得到这个工作。如果我调试并手动步进数组,它会工作,但当我不步进它(I。(让程序运行)抛出这些错误

编辑:前10行数据如下:
654603年

640583年

587672年

627677年

613711年

612717年

584715年

573662年

568662年

564687年

文本文件中没有空行。

正如Jon Skeet所指出的,删除临时赋值似乎已经修复了这个错误。然而,即使有了这些任务,它仍然应该是有效的。下面的代码示例在while循环中工作:

string[] temp;
temp = line.Split(',');
trees[count].X = Convert.ToInt16(temp[0]);
trees[count].Y = Convert.ToInt16(temp[1]);
count++;

树的数量是已知的,但我想感谢每个人的输入。预计在不久的将来会有更多的问题:D

从c#中的.txt文件中读取x,y值

尝试在trees集合中使用List<Point>而不是数组。如果你事先不知道正确的计数,这将会很有帮助。

var trees = new List<Point>();
while (...)
{
    ...
    trees.Add(new Point(x, y));
}

第二个可能的问题是输入行不包含有效数据(例如,为空)。通常数据的最后一行以换行符结束,因此最后一行为空。

while ((line = coordStream.ReadLine()) != null)
{
    var temp = line.Split(',');
    if (temp.Length != 2)
        continue;
    ....
}
var lineContents = File.ReadAllLines("").Select(line => line.Split(',')).Where(x => x.Count() == 2);
var allTrees = lineContents.Select(x => new Trees() { X = Convert.ToInt16(x[0]), Y = Convert.ToInt16(x[1]) });