1

What I am doing is reading in from a text file, and then storing the contents in a 2D array, but my array is off by one at each row and column. Maybe this is simple and I am just not seeing it?

The contents of my text file:

0007,0007,0007,0007,0007,
0007,0007,0007,0007,0007,
0007,0007,0007,0007,0007,
0007,0007,0007,1707,0007,
0007,0007,0007,0007,0401

When my array is returned, the value 17 is located at [3,3]...it should be [4,4]. Below is my code. I've spent to much time on this already, could someone please help?

public int[,] Generate(string inputFilePath)
{
    if (File.Exists(inputFilePath))
    {
        Dictionary<string, int> counts = GetRowAndColumnCounts(inputFilePath);

        int rowCount = counts["row_count"];
        int columnCount = counts["column_count"];

        returnArray = new int[rowCount, columnCount];

        using (StreamReader sr = File.OpenText(inputFilePath))
        {
            string s = "";
            string[] split = null;

            for (int i = 0; (s = sr.ReadLine()) != null; i++)
            {
                split = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                for (int j = 0; j < columnCount; j++)
                {
                    returnArray[i, j] = int.Parse(split[j].Substring(0,2));
                }
            }
        }
    }
    else
    {
        // throw new FileDoesNotExistException("Input file does not exist");
    }
    return returnArray;
}
3
  • 7
    From where I see it, the result is fine. Array indexes start at 0, not 1 , so 1707 which is on the 4th line and 4th column is actually at index 3,3. Commented Apr 8, 2014 at 15:21
  • 1 based indexes are the devil. Repeat that every night and morning. Commented Apr 8, 2014 at 15:27
  • OF course I knew that the arrays are zero based. But thank you for confirming the code was correct. Turns out that this wasn't the offending piece of code after all for the issue I was having. Its all good now that Ive tracked down the real issue. Thanks. Commented Apr 12, 2014 at 8:35

1 Answer 1

1

Array indexes start at 0. So index 3 is the 4. element.

http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

C# arrays are zero indexed; that is, the array indexes start at zero.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.