How to read char from the console
Asked Answered
P

4

9

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.Length; i++)
{
    input[i] = Console.ReadLine();
}

But I'm getting the following error:

Cannot implicitly convert type 'System.ConsoleKeyInfo' to 'char'

Is there an easy way to fix this?

Polynesian answered 8/11, 2013 at 13:51 Comment(2)
Did you have a look at what System.ConsoleKeyInfo is? Hint: msdn.microsoft.com/en-us/library/…Cespitose
possible duplicate of Difference between Console.Read() and Console.ReadLine()?Poindexter
F
36

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;
Funicular answered 8/11, 2013 at 13:53 Comment(1)
Fails if stdin comes from a file though.Foresight
I
2

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();
    }
Incase answered 8/11, 2013 at 13:59 Comment(0)
B
0

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.

Bummer answered 8/1, 2020 at 18:46 Comment(0)
L
0
public static int MyAnswer(int n)
{
  int[] ac = new int[n];

  for (int i = 0; i < ac.Length; i++) {
  
  ac[i] = char.Parse(Console.ReadLine());

  Console.WriteLine(ac[i]);
 }
 return 0;
}


  
Lunate answered 30/6, 2022 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.