Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disallow all non-numeric input in console during an input prompt?

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?

like image 330
Precision Avatar asked Mar 18 '11 15:03

Precision


2 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
  }
}
like image 182
Skizz Avatar answered Nov 14 '22 17:11

Skizz


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");
}
like image 1
MaLio Avatar answered Nov 14 '22 18:11

MaLio