繁体   English   中英

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

[英]Reading x,y values from a .txt file in c#

我正在尝试将文本文件中的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++;
 }

我知道这似乎是一个琐碎的错误,但是我似乎无法正常工作。 如果我手动调试并逐步遍历该数组,则可以工作,但是当我不逐步遍历(即让程序运行)时,将抛出这些错误

编辑:数据的前10行如下:

654,603

640,583

587,672

627,677

613,711

612,717

584,715

573,662

568,662

564,687

文本文件中没有空行。

正如乔恩·斯凯特(Jon Skeet)指出的那样,删除临时分配似乎已解决了该错误。 但是,即使进行了分配,它也应该仍然有效。 while循环中的以下代码示例有效:

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

树的数量是已知的,但我要感谢大家的投入。 在不久的将来会期望更多的问题:D

尝试将List<Point>用于trees集合而不是数组。 如果您不预先知道正确的计数,这将有所帮助。

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]) });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM