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
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);
}
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);
}
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With