如何在 C# 控制台中单行读取矩阵行元素

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

我想从控制台的输入中读取一个 5 X 5 矩阵,并且我想在一行中而不是在单独的行中读取行元素,如下所示:

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

多行版本:

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;
    }

单行版本:

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;
}

我认为这会有所帮助:reading two integers in one line using C#

基本上是 string[] tokens = Console.ReadLine().Split();,然后您可以调用 tokens.Length 来查看将有多少列。

我用这个函数来读取元素

    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);
    }

那么我们只需要一个循环来读取这样的元素

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