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?

David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
Martin Dzhonov
  • 1,021
  • 4
  • 15
  • 28
  • Did you have a look at what `System.ConsoleKeyInfo` is? Hint: http://msdn.microsoft.com/en-us/library/system.consolekeyinfo%28v=vs.110%29.aspx – germi Nov 08 '13 at 13:52
  • possible duplicate of [Difference between Console.Read() and Console.ReadLine()?](http://stackoverflow.com/questions/6825943/difference-between-console-read-and-console-readline) – Liam Nov 08 '13 at 13:53

4 Answers4

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;
David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
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();
    }
Kjartan
  • 18,591
  • 15
  • 71
  • 96
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.

ctg
  • 1
  • 1
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;
}