Talking console here.
The idea is that if user presses any key except numbers(the ones above the letter keys, and numpad) during an input prompt in the console, then nothing will be 开发者_开发知识库typed. Its's as if console will ignore any non-numeric key presses.
How would one do it the right way?
Try the ReadKey method:
while (processing input)
{
ConsoleKeyInfo input_info = Console.ReadKey (true); // true stops echoing
char input = input_info.KeyChar;
if (char.IsDigit (input))
{
Console.Write (input);
// and any processing you may want to do with the input
}
}
private static void Main(string[] args) {
bool inputComplete = false;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
while (!inputComplete ) {
System.ConsoleKeyInfo key = System.Console.ReadKey(true);
if (key.Key == System.ConsoleKey.Enter ) {
inputComplete = true;
}
else if (char.IsDigit(key.KeyChar)) {
sb.Append(key.KeyChar);
System.Console.Write(key.KeyChar.ToString());
}
}
System.Console.WriteLine();
System.Console.WriteLine(sb.ToString() + " was entered");
}
This little experiment works like that:
static void Main()
{
while (true)
{
var key = Console.ReadKey(true);
int i;
if (int.TryParse(key.KeyChar.ToString(), out i))
{
Console.Write(key.KeyChar);
}
}
}
精彩评论