Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Check if ConsoleKeyInfo.KeyChar is a number

Tags:

c#

input

ConsoleKeyInfo CKI = Console.ReadKey(true);

CKI.KeyChar is the unicode equivalent of the character input So if I'd press '1' in the console prompt CKI.KeyChar would be 49, not the value '1'.

How do I get the value '1'?

I know its a devious way of getting the input, but its the way my teacher wants it so I cant do it otherwise.

Edit: I need the value that the user gave, because I'm going to have to check if its less than 9

like image 868
user1534664 Avatar asked Sep 28 '12 17:09

user1534664


2 Answers

Use the .KeyChar property and compare with Char.IsNumber.

To get the numeric equivalent, you can use Int32.Parse or Int32.TryParse:

Int32 number;
if (Int32.TryParse(cki.KeyChar.ToString(), out number))
{
  Console.WriteLine("Number: {0}, Less than 9?: {1}", number, number < 9);
}

Test Application:

using System;

namespace Test
{
    public static void Main()
{
    Console.WriteLine("Press CTRL+C to exit, otherwise press any key.");
    ConsoleKeyInfo cki;
    do
    {
        cki = Console.ReadKey(true);
        if (!Char.IsNumber(cki.KeyChar))
        {
            Console.WriteLine("Non-numeric input");
        }
        else
        {
            Int32 number;
            if (Int32.TryParse(cki.KeyChar.ToString(), out number))
            {
                Console.WriteLine("Number received: {0}; <9? {1}", number, number < 9);
            }
            else
            {
                Console.WriteLine("Unable to parse input");
            }
        }
    }
    while (cki.KeyChar != 27);
}
}
like image 101
Brad Christie Avatar answered Sep 19 '22 01:09

Brad Christie


Use this:

char.IsDigit(CKI.KeyChar);

If you need to convert it into a number, use this:

int myNumber = int.Parse(CKI.KeyChar.ToString())

To check if its less than 9, then you do this:

if (myNumber < 9)
{
     // Its less than 9. Do Something
} else {
     // Its not less than 9. Do something else
}
like image 35
Icemanind Avatar answered Sep 20 '22 01:09

Icemanind