How to read char from the console

后端 未结 3 999
春和景丽
春和景丽 2020-12-03 22:27

I have a char array and I want to assign values from the console. Here\'s my code:

char[] input = new char[n];
for (int i = 0; i < input.Leng         


        
相关标签:
3条回答
  • 2020-12-03 22:41

    Use Console.ReadKey and then KeyChar to get char, because ConsoleKeyInfo is not assignable to char as your error says.

    input[i] = Console.ReadKey().KeyChar;
    
    0 讨论(0)
  • 2020-12-03 22:49

    Quick example to play around with:

        public static void DoThis(int n)
        {
            var input = new char[n];
            for (var i = 0; i < input.Length; i++)
            {
                input[i] = Console.ReadKey().KeyChar;
            }
    
            Console.WriteLine(); // Linebreak
            Console.WriteLine(input);
    
            Console.ReadKey();
        }
    
    0 讨论(0)
  • 2020-12-03 22:54

    Grab the first character of the String being returned by Console.ReadLine()

    char[] input = new char[n];
    for (int i = 0; i < input.Length; i++)
    {
        input[i] = Console.ReadLine()[0];
    }
    

    This will throw away all user input other than the first character.

    0 讨论(0)
提交回复
热议问题