How to prevent all non-numeric inputs in the console during input?

Talking console here.

The idea is that if the user presses any key except the numbers (the ones above the letter and numpad keys) while entering input in the console, nothing will be printed. As if the console would ignore any non-numeric keystrokes.

How to do it right?

+6
c # input validation console
source share
3 answers

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 } } 
+9
source share
 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"); } 
+1
source share

This little experiment works like this:

 static void Main() { while (true) { var key = Console.ReadKey(true); int i; if (int.TryParse(key.KeyChar.ToString(), out i)) { Console.Write(key.KeyChar); } } } 
0
source share

All Articles