简体   繁体   English

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

[英]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: 我想从控制台的输入中读取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

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

I think this could help: reading two integers in one line using C# 我认为这可能会有所帮助: 使用C#在一行中读取两个整数

Basicly the string[] tokens = Console.ReadLine().Split(); 基本上, string[] tokens = Console.ReadLine().Split(); and then you could call tokens.Length to see how many columns there r going to be. 然后您可以调用tokens.Length来查看有多少列。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM