Search code examples
c#inputuser-inputreadkey

How can I limit user input to a single alpha character in c#?


I'm using the following code to accept user input. I want to limit user input to a single alpha (a-z) character only. I'm finding a lot of validations using IsNumber to validate integer input, and a lot of information about using a regex on an input String, but I've been unable to uncover how I would be able to restrict input possibilities with this code. Can someone point me in the right direction?

    public char promptForGuess()
    {
        Console.Write("\nGuess a letter: ");
        String pre = Console.ReadKey().Key.ToString();
        string pre2 = pre.ToUpper();
        char pre3 = Convert.ToChar(pre2);
    }

Solution

  • You cannot limit the user only put in a-z chars on the console - you have to check the input, he can write in any character (just think about when the input is redirected to your program from a file with <, e.g. yourapp.exe < input.dat ).

    But its easy to check a character is lowercase a-z letter. E.g. with plain, ASCII, C tactic (I will use your defined variables):

    if('A' <= pre3 && pre3 <'Z') { // pre3 was made upper in your code
        // input OK
    } else {
        // input NOK
    }
    

    With regex:

    Regex r = new Regex(@"^[a-zA-Z]$");
    return r.IsMatch(pre);
    

    If you cannot allow case-insensitive characters, just change the code I wrote.

    Anyway, I think you need Console.Read() (ReadKey also read keys like arrows, F1-F12 etc..., so ALL keys, even tab and caps lock). Refer to MSDN: http://msdn.microsoft.com/en-us/library/system.console.read.aspx

    And maybe you should use this function, if you would support unicode letters: http://msdn.microsoft.com/en-us/library/yyxz6h5w.aspx Note that unicode letters are usually not one bytes! But char can store it. These letters are for example beautiful Hungarian letters with acutes and these king of things: á, é, ő, ű, ö, ü etc (but also French have a lot, and also Dutch etc...)