【问题标题】:Error when pressing the Enter key, C# console按 Enter 键时出错,C# 控制台
【发布时间】:2013-11-20 19:59:41
【问题描述】:

我的代码要求用户输入一个字母(将 string 转换为 char),但是当按 Enter 键作为输入时,代码会崩溃。

我没有设置任何条件来向用户发送错误消息以在输入时不按 Enter 键并且只输入字母。

这是我正在努力解决的部分:

public static char GetLetter(string prompt)
{
    char result;

    Console.Write("\n\t" + prompt + ":  ");
    result = Convert.ToChar(Console.ReadLine());

    if(result == '!' || result == '@' || result == '#'  || result == '$' || result == '%'  )
    // we can keep going with all the unwanted characters and numbers 
    {
        Console.WriteLine("\n\t NO MATCH ! \n\t ,please try again using letters only , ");
        result = GetLetter(prompt);
        return result;
    }

    return result;
}

【问题讨论】:

  • 我们需要查看实际的错误和输入。
  • Console.ReadKey 可以做到,不是吗?
  • @AlexandreTryHardLeblanc,正是我要去的地方;而且是更正确的做法,但我还是对实际的错误和输入有点好奇。

标签: c# error-handling key enter


【解决方案1】:

Console.ReadLine() 将返回 string,而不是 char,请改用 Console.Read。检查来自 MSDN 的details

【讨论】:

    【解决方案2】:

    输入时出现错误,因为你得到一个空字符串,所以你不能把它转换成char。

    我愿意让你这样做:

    char result;
    string input = Console.ReadLine();
    
    if (char.TryParse(input, out result))
    {
        //The input is a char - write your code here.
    }
    
    //The input is not a char.
    

    【讨论】:

    • 你知道让用户只输入字母的更好方法吗?因为我认为我的代码看起来很奇怪||或:/
    • 可以使用 IsLetter 方法,像这样:if (char.IsLetter(result))
    【解决方案3】:

    您可以使用Console.ReadKey()函数读取字符如下:

    public static char GetLetter(string prompt)
    {
        char result;
    
        Console.Write("\n\t" + prompt + ":  ");
        result = Console.ReadKey().KeyChar;
    
        if (result == '!' || result == '@' || result == '#' || result == '$' || result == '%')
        // we can keep going with all the unwanted characters and numbers 
        {
            Console.WriteLine("\n\t NO MATCH ! \n\t ,please try again using letters only , ");
            result = GetLetter(prompt);
            return result;
        }
    
        return result;
    }
    

    【讨论】:

    • 啊,当我按下任何不需要按 Enter 键的字母键时,它给了我结果。这也很好,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多