0

If I create a 2d array like so:

int[,] MyArray = new int[5, 5];

and have a text file with these numbers:

1 2 3 4 5

5 4 3 2 1

1 2 3 4 5

2 3 4 6 7

7 8 9 6 4

How do I get the numbers into the 2d array?

3 Answers 3

2

This should be fairly straightforward. Nested loops are the "traditional" way to handle multidimensional arrays.

Nest two loops, the outer iterating over lines in the input, the inner over numbers in a line.

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

Comments

1

string[] line = text.split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < line.Length; i++)
{
    string[] digit = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    for (int j = 0; j < digit.Length; j++)
    {
        MyArray[i, j] = Convert.ToInt32(digit[j]);
    }
}

Comments

0

However you want...

Basically you have to decide.

Here is a heuristic:

  • Read in the file
  • Parse the numbers
  • Calculate the sizes of the arrays
  • Insert the numbers in the appropriate locations.

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.