Javad
Javad

Reputation: 63

how to read matrix row elements in single line in C# console

I want to read a 5 X 5 matrix from input in console and I want to read row elements in a single line and not in separate lines, like this:

25 16 14 12
10 15 11 10
2 10 9 8 8
7 6 11 20
5 4 1 0 3

Upvotes: 0

Views: 4446

Answers (3)

Javad
Javad

Reputation: 63

i used this function to read elements

    static int readIndex()
    {
        string num = string.Empty;
        ConsoleKeyInfo cr;
        do
        {
            cr = Console.ReadKey(true);
            int n;
            if (int.TryParse(cr.KeyChar.ToString(), out n))
            {
                num += cr.KeyChar.ToString();
                Console.Write(cr.KeyChar.ToString());
            }
            else if (cr.Key == ConsoleKey.Backspace)
            {
                if (num.Length > 0)
                {
                    Console.Write("\b");
                    num = num.Remove(num.Length - 1);
                }
            }

        } while (cr.Key != ConsoleKey.Enter);
        Console.Write("  ");
        return int.Parse(num);
    }

then we need just a loop to read elements like this

        for (int i = 0; i < 5; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                mat[i, j] = (int)readIndex();
            }
            Console.WriteLine();
        }

Upvotes: 0

a-ctor
a-ctor

Reputation: 3733

Multi line version:

private static int[,] ReadMatrix()
    {
        var mtr = new int[5, 5];
        for (var i = 0; i < 5; i++)
        {
            var line = Console.ReadLine();
            var spl = line.Split(' ');
            if (spl.Length != 5) throw new FormatException();
            for (var j = 0; j < 5; j++)
                mtr[i, j] = int.Parse(spl[j]);
        }
        return mtr;
    }

Single line version:

private static int[,] ReadMatrix()
{
    var mtr = new int[5, 5];
    var line = Console.ReadLine();
    if (string.IsNullOrWhiteSpace(line)) throw new FormatException();
    var spl = line.Split(' ');
    if (spl.Length != 25) throw new FormatException();
    for (var i = 0; i < 25; i++)
        mtr[i/5, i%5] = int.Parse(spl[i]);
    return mtr;
}

Upvotes: 3

Dashovsky
Dashovsky

Reputation: 137

I think this could help: reading two integers in one line using C#

Basicly the string[] tokens = Console.ReadLine().Split(); and then you could call tokens.Length to see how many columns there r going to be.

Upvotes: 0

Related Questions