Accept only numbers in the C#console app

Asked

Viewed 820 times

4

Good evening, I’m trying to get the Console.Readline() command to read only numbers, ignoring characters, there’s a way ?

example:

static void main()
{
    int x;

    Console.WriteLine("INSERINDO VALOR PARA X");

    x=int.Parse(Console.ReadLine()) //em execução quero que o console só aceite números inteiros do teclado.

}
  • Thanks a lot for the resolutions, I managed to implement in my code, but I’m having difficulties to delete the key that was typed, in case of wrong click. I changed this code to recognize the bad Backspace it crashes the console.

  • But this comment is directed to whom? To me or to Daniel. When so do the comment in the reply by pressing the button comentar below the reply, that thus the author of the reply will be notified.

  • If it’s C# why the C tag?

2 answers

4

Gabriel, if there’s any native way to do this, I’m sorry but I don’t know.

Generally, people adopt a loop that keeps the user "stuck" while what they type is not a number, and the cast is done in a way that does not create an exception.

Take an example:

using System;

class ReadLineInt {
  static void Main() {
    int x;

    Console.WriteLine("INSERINDO VALOR PARA X");

    while(!int.TryParse(Console.ReadLine(), out x)) {
         Console.WriteLine("Insira apenas números inteiros");
         Console.WriteLine("INSERINDO VALOR PARA X");
    }

    Console.WriteLine("Número digitado: " + x);
  }
}
  • Interesting, I will adapt this example to see how it looks, thank you very much.

1


You can implement a method that reads exclusively numbers pressed within the Console. For this you will have to start a loop and have to test each iteration if a key was pressed with Console.KeyAvailable which returns a boolean indicating if there has been the pressing of a key.

If Console.KeyAvailable To charge a keystroke is to instruct the reading of the key with Console.ReadKey(); passing by true as the first parameter to prevent the read key from being printed on the 'Console' screen'.

Then test the nature of the pressed key:

  • If it’s a number accumulate in the string return method.

  • If the enter key ends the iteration.

  • If the back space key removes the last character from the console (see code settings).

  • Any other value ignore.

Using switch case when with the syntax of version 7 or higher of C#:

using System;

class Exemplo
{
    public static string lerNumeros()
    {
        ConsoleKeyInfo cki;
        string entrada = "";
        bool continuarLoop = true;
        while (continuarLoop)
            if (Console.KeyAvailable)
            {
                cki = Console.ReadKey(true);
                switch (cki.Key)
                {
                    case ConsoleKey.Backspace:
                        if (entrada.Length == 0) continue;
                        entrada = entrada.Remove(entrada.Length - 1);
                        Console.Write("\b \b"); //Remove o último caractere digitado
                        break;
                    case ConsoleKey.Enter:
                        continuarLoop = false;
                        break;
                    case ConsoleKey key when ((ConsoleKey.D0 <= key) && (key <= ConsoleKey.D9) ||                       
                                              (ConsoleKey.NumPad0 <= key) && (key <= ConsoleKey.NumPad9)):
                        entrada += cki.KeyChar;
                        Console.Write(cki.KeyChar);
                        break;
                }
            }
        return entrada;
    }
    public static void Main()
    {
        Console.WriteLine("Insira o valor para X.");


        int x = int.Parse(lerNumeros());

        Console.WriteLine("\nO valor de X é '{0}'.", x);

        Console.ReadKey();

    }
}

Using if independent of the language version:

using System;

class Exemplo
{
    public static string lerNumeros()
    {
        ConsoleKeyInfo cki;
        string entrada = "";            
        while (true)
            if (Console.KeyAvailable)
            {
                cki = Console.ReadKey(true);
                if (cki.Key == ConsoleKey.Backspace){
                    if (entrada.Length == 0) continue;
                    entrada = entrada.Remove(entrada.Length - 1);
                    Console.Write("\b \b"); //Remove o último caractere digitado
                }    
                if (cki.Key == ConsoleKey.Enter)
                {
                    break;
                }
                if ((ConsoleKey.D0 <= cki.Key) && (cki.Key <= ConsoleKey.D9) ||
                    (ConsoleKey.NumPad0 <= cki.Key) && (cki.Key <= ConsoleKey.NumPad9))
                {
                    entrada += cki.KeyChar;
                    Console.Write(cki.KeyChar);
                }

            }
        return entrada;
    }

    public static void Main()
    {
        Console.WriteLine("Insira o valor para X.");


        int x = int.Parse(lerNumeros());

        Console.WriteLine("\nO valor de X é '{0}'.", x);

        Console.ReadKey();

    }
}

Code in the Repl.it

  • 1

    I managed to solve my problem with these examples, just missing the part of including the Backspace that I’m still checking. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.