Home > database >  Way to input entire 2D array at once in C#?
Way to input entire 2D array at once in C#?

Time:10-23

I wrote this code for a 1D array:

int[] arr= new int[9];
arr=Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse)

It takes my whole input at once and converts it as an array besides removing spaces. Where input is 1 2 3 4 5 6 7 8 9.

This same concept was tried for 2D arrays but still can't match. Here is my code,

int[,] arr = new int[3, 3];

for (int i = 0; i < 3; i  )
{
    for (int j = 0; j < 3; j  )
    {
        arr[i, j] =Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
    }
}

My input is:

1 2 3
4 5 6
7 8 9

What is the solution? How can I input the entire 2D array at once in C#?

CodePudding user response:

You should call Console.ReadLine for every line and then put in the values:

int[,] arr = new int[3, 3];

for (int i = 0; i < 3; i  )
{
    int[] temp = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);

    for (int j = 0; j < 3; j  )
    {
        arr[i, j] = temp[j];
    }
}
  • Related