C # Check if ConsoleKeyInfo.KeyChar is a number

ConsoleKeyInfo CKI = Console.ReadKey(true); 

CKI.KeyChar is the unicode equivalent of entering characters. Therefore, if I pressed "1" in a console request, CKI.KeyChar would be 49, not the value "1".

How do I get the value "1"?

I know his sophisticated way to get input, but his way my teacher wants it, so I can't do it otherwise.

Edit: I need the value that the user gave, because I will need to check if it is not less than <9

+4
source share
4 answers

Use the .KeyChar property and compare it to Char.IsNumber .

To get the numerical 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); } 

Application for testing:

 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); } } 
+4
source

Use this:

 char.IsDigit(CKI.KeyChar); 

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

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

To check if it is less than 9, do the following:

 if (myNumber < 9) { // Its less than 9. Do Something } else { // Its not less than 9. Do something else } 
+5
source

49 is just ascii code, so you can make char c = (char) 49 and get the actual character.

0
source

You can do this in a simple way (see below), or you can use the ConsoleKey enumeration to determine which key was pressed - ConsoleKey.D[0-9] - ordinary decimal numeric keys and ConsoleKey.NumPad[0-9] keys numeric keypad. You might want to check which modifiers were pressed using enum ConsoleModifiers . This enumeration has the Flags attribute, so the values ​​can be combined with a bitwise OR. For example, if the ConsoleKeyInfo.Modifiers property is ConsoleModifiers.Control|ConsoleModifiers.Alt , the user pressed the [CTL] and [ALT] keys along with any other keystroke.

 public static void Main( string[] args ) { Console.TreatControlCAsInput = true ; Console.Write("? ") ; while ( true ) { ConsoleKeyInfo keystroke = Console.ReadKey() ; Console.WriteLine(); if ( keystroke.Modifiers == ConsoleModifiers.Control && keystroke.Key == ConsoleKey.C ) break ; int decimalDigit = ((int)keystroke.KeyChar) - ((int)'0') ; if ( decimalDigit >= 0 && decimalDigit <= 9 ) { Console.WriteLine("Decimal Digit {0}", decimalDigit ) ; } else { Console.WriteLine( "Not a decimal digit!" ) ; } Console.Write("? ") ; } return; } 
0
source

Source: https://habr.com/ru/post/1436864/


All Articles