【问题标题】:How to read char from the console如何从控制台读取字符
【发布时间】:2013-11-20 13:24:21
【问题描述】:

我有一个char 数组,我想从控制台分配值。这是我的代码:

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

但我收到以下错误:

无法将类型“System.ConsoleKeyInfo”隐式转换为“char”

有没有简单的方法来解决这个问题?

【问题讨论】:

标签: c#


【解决方案1】:

使用Console.ReadKey 然后KeyChar 得到char,因为ConsoleKeyInfo 不能分配给char,正如您的错误所说。

input[i] = Console.ReadKey().KeyChar;

【讨论】:

  • 如果标准输入来自文件则失败。
【解决方案2】:

快速示例:

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

【讨论】:

    【解决方案3】:

    获取 Console.ReadLine() 返回的字符串的第一个字符

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

    这将丢弃除第一个字符之外的所有用户输入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 2013-07-20
      • 2011-02-06
      相关资源
      最近更新 更多