Home > Back-end >  2D Array Input in same line
2D Array Input in same line

Time:10-26

How I take 2D array input in same line. in C# Console.ReadLine() allow us to take input one at a time .I want to take input as a row

int [,] arr = new int[m,n];

for(i = 0; i < m; i  )
{
    for(j = 0; j < n; j  )
    {
        arr[i, j] = int.Parse(Console.ReadLine());
    }
}

I want to take input this way 2 2, 10 20, 30 40

CodePudding user response:

    for(var i = 0; i<n; i  ) {
        var row = Console.ReadLine();
        var _arr = row.Trim().Split(' ');
        for(var j=0; j<m; j  ) {
            arr[j, i] = int.Parse(_arr[j].Trim());
        }
    }

CodePudding user response:

Entering a two-dimensional array on the command line is going to be error prone and frustrating for users. But if you MUST do it:

  1. Figure out what symbols will separate values. (Commas, spaces?)
  2. Figure out what symbols will separate array dimensions. (Pipes, perhaps? Whatever you choose, make sure it isn't the same symbol you use for separating values.)
  3. Prompt the user for data and capture it into a string.
  4. Validate the data.
  5. Write a parser that parses your data into a multi-dimensional array.

I'd advise against trying to do this. But I don't dictate your requirements.

  • Related