C# Console.ReadKey read numbers greater than 9

5.1k Views Asked by At

Im working with ConsoleKeyInfo in C# but i have problems with Console.ReadKey when I try to write numbers greater than 9 in the console, for example

ConsoleKeyInfo number;
Console.Write("Write a number: ");
number = Console.ReadKey();

If i want to write 10 or 11... the console only reads the "1"

I dont wanna use Console.ReadLine because I don want to press "Enter" for each number.

Is there another way to use Console.ReadKey to wait maybe 1 second before continue?

Thanks

3

There are 3 best solutions below

9
On

The best you can do is use Console.ReadLine(). There's no way the program will know you have finished the number.

UPDATE

If you have a fixed length number (i.e. a 13-digit ISBN), you can use ReadKey, but like this:

string isbn = "";
while (isbn.Length < 13)
{
    isbn += Console.ReadKey().KeyChar;
}
0
On

As the comments on the question say, Console.ReadKey only reads a single key by definition. You will need to use a different function if you want to get more input from the console. Try something like this, for instance:

Console.Write("Write a number: ");
string line = Console.ReadLine();
int num = 0;
if (line != null)
    num = int.Parse(line);

That's a start, with minimal error checking. See what you can get from there.

0
On

The idea is that you have to call cki = Console.ReadKey(true) multiple times.

      ConsoleKeyInfo cki;
      string userNumber = "";

      while(true)
      {
        System.Console.WriteLine("Press more than one key:");
        cki = Console.ReadKey(true);

        if(cki.Key == ConsoleKey.Escape)
        {
          System.Console.WriteLine("GOOD BYE!");
          Environment.Exit(0);
        }
        else
        {
          if(char.IsNumber(cki.KeyChar) || cki.Key == ConsoleKey.Enter)
          {
            while(char.IsNumber(cki.KeyChar))
            {
              Console.Write(cki.KeyChar);
              userNumber += (cki.KeyChar).ToString();
              cki = Console.ReadKey(true);  // !!! Main idea 
            }
              System.Console.WriteLine();
              System.Console.WriteLine($"Your number is: {userNumber}");
              Environment.Exit(0);
          } 
          else
          {
            System.Console.WriteLine("Wrong symbol! Input a number!");
          }
        }
      }