Note that there are some explanatory texts on larger screens.

plurals
  1. POReading x,y values from a .txt file in c#
    text
    copied!<p>I'm trying to read x and y values from a text file into a string array where the line is being split on the ',' However, when I run this code I get an error saying the index was out of the bounds of the array on the first element. I've tried using temporary strings to store the data and then convert them but I still get the same error on the second element. here is my code I have implemented without the temporary strings.</p> <pre><code>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++; } </code></pre> <p>Here is the code with the temporary storage too:</p> <pre><code>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++; } </code></pre> <p>I know this seems a trivial error but I cannot seem to get this working. If I debug and step through the array manually it works but when I don't step through it(i.e let the program run) these errors are thrown</p> <p>EDIT: The first 10 lines of data are as follows:</p> <blockquote> <blockquote> <p>654,603</p> <p>640,583</p> <p>587,672</p> <p>627,677</p> <p>613,711</p> <p>612,717</p> <p>584,715</p> <p>573,662</p> <p>568,662</p> <p>564,687</p> </blockquote> </blockquote> <p>There are no empty lines in the text file.</p> <p>As pointed out by Jon Skeet, removing the temp assignments seems to have fixed this error. However even with the assignments it should still have worked. The following code sample inside the while loop works: </p> <pre><code>string[] temp; temp = line.Split(','); trees[count].X = Convert.ToInt16(temp[0]); trees[count].Y = Convert.ToInt16(temp[1]); count++; </code></pre> <p>The number of trees is known but I'd like to thank everyone for their input. Expect more questions in the near future :D</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload