13
Console.WriteLine("Enter the cost of the item");                           
string input = Console.ReadLine();
double price = Convert.ToDouble(input);

Hello, I want the keyboard buttons, A-Z, brackets, question mark, etc to be disabled. I want it so if you type it in, it will not show up in the Console. I only want the numbers 1-9 to show up. This is in C# Console application. Thanks for the help!

maccettura
  • 10,514
  • 3
  • 28
  • 35
Sarah
  • 183
  • 1
  • 1
  • 10

7 Answers7

15

try this code snippet

string _val = "";
Console.Write("Enter your value: ");
ConsoleKeyInfo key;

do
{
    key = Console.ReadKey(true);
    if (key.Key != ConsoleKey.Backspace)
    {
        double val = 0;
        bool _x = double.TryParse(key.KeyChar.ToString(), out val);
        if (_x)
        {
            _val += key.KeyChar;
            Console.Write(key.KeyChar);
        }
    }
    else
    {
        if (key.Key == ConsoleKey.Backspace && _val.Length > 0)
        {
            _val = _val.Substring(0, (_val.Length - 1));
            Console.Write("\b \b");
        }
    }
}
// Stops Receving Keys Once Enter is Pressed
while (key.Key != ConsoleKey.Enter);

Console.WriteLine();
Console.WriteLine("The Value You entered is : " + _val);
Console.ReadKey();
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • 1
    i modified some code on the net the suit your needs. anyway, welcome to stackOverFlow! – John Woo Oct 28 '12 at 05:12
  • 2
    I looked back at this, and it helped me with another question. As I learn more C#, I understand more of what you were doing. I do have a long way to go though before I understand all of this! – Sarah Nov 08 '12 at 02:31
  • @491243 I tested your sleek code snippet. In order for it to work correctly as you intended, it **must be followed** by the `Console.WriteLine();` at the end. At first I missed that out and took me 1 hour to figure what's going wrong. Nice code! – aspiring Sep 22 '13 at 07:15
  • 1
    You could improve this answer by putting in some additional comments that help explain how and why your code works. I ended up figuring it out by playing around with it, but still... For example, the fact that the boolean argument value of `true` in `Console.ReadKey(true);` is necessary to prevent other keys from being displayed. – rory.ap Sep 25 '15 at 12:20
4

In a while, I got a solution really short:

double number;
Console.Write("Enter the cost of the item: ");
while (!double.TryParse(Console.ReadLine(), out number))
{
   Console.Write("This is not valid input. Please enter an integer value: ");
}

Console.Write("The item cost is: {0}", number);                          

See you!

yasserpulido
  • 198
  • 1
  • 2
  • 11
3

This MSDN article explains how to read characters one at a time in a console window. Test each character as it is input with the Char.IsNumber() method, and reject those characters that fail the test.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
1

Here is one approach. It's probably overkill if you're just starting out in C#, since it uses some more advanced aspects of the language. In any case, I hope you find it interesting.

It has some nice features:

  • The ReadKeys method takes an arbitrary function for testing whether the string so far is valid. This makes it easy to reuse whenever you want filtered input from the keyboard (e.g. letters or numbers but no punctuation).

  • It should handle anything you throw at it that can be interpreted as a double, e.g. "-123.4E77".

However, unlike John Woo's answer it doesn't handle backspaces.

Here is the code:

using System;

public static class ConsoleExtensions
{
    public static void Main()
    {
        string entry = ConsoleExtensions.ReadKeys(
            s => { StringToDouble(s) /* might throw */; return true; });

        double result = StringToDouble(entry);

        Console.WriteLine();
        Console.WriteLine("Result was {0}", result);
    }

    public static double StringToDouble(string s)
    {
        try
        {
            return double.Parse(s);
        }
        catch (FormatException)
        {
            // handle trailing E and +/- signs
            return double.Parse(s + '0');
        }
        // anything else will be thrown as an exception
    }

    public static string ReadKeys(Predicate<string> check)
    {
        string valid = string.Empty;

        while (true)
        {
            ConsoleKeyInfo key = Console.ReadKey(true);
            if (key.Key == ConsoleKey.Enter)
            {
                return valid;
            }

            bool isValid = false;
            char keyChar = key.KeyChar;
            string candidate = valid + keyChar;
            try
            {
                isValid = check(candidate);
            }
            catch (Exception)
            {
                // if this raises any sort of exception then the key wasn't valid
                // one of the rare cases when catching Exception is reasonable
                // (since we really don't care what type it was)
            }

            if (isValid)
            {
                Console.Write(keyChar);
                valid = candidate;
            }        
        }    
    }
}

You also could implement an IsStringOrDouble function that returns false instead of throwing an exception, but I leave that as an exercise.

Another way this could be extended would be for ReadKeys to take two Predicate<string> parameters: one to determine whether the substring represented the start of a valid entry and one the second to say whether it was complete. In that way we could allow keypresses to contribute, but disallow the Enter key until entry was complete. This would be useful for things like password entry where you want to ensure a certain strength, or for "yes"/"no" entry.

Matthew Strawbridge
  • 19,940
  • 10
  • 72
  • 93
0

This code will allow you to:

  • Write only one dot (because numbers can have only one decimal separator);
  • One minus at the begining;
  • One zero at the begining.

It means that you not be able to write something like: "00000.5" or "0000...-5".

class Program
{
    static string backValue = "";
    static double value;
    static ConsoleKeyInfo inputKey;

    static void Main(string[] args)
    {
        Console.Title = "";
        Console.Write("Enter your value: ");

        do
        {
            inputKey = Console.ReadKey(true);

            if (char.IsDigit(inputKey.KeyChar))
            {
                if (inputKey.KeyChar == '0')
                {
                    if (!backValue.StartsWith("0") || backValue.Contains('.'))
                        Write();
                }

                else
                    Write();
            }

            if (inputKey.KeyChar == '-' && backValue.Length == 0 ||
                inputKey.KeyChar == '.' && !backValue.Contains(inputKey.KeyChar) &&
                backValue.Length > 0)
                Write();

            if (inputKey.Key == ConsoleKey.Backspace && backValue.Length > 0)
            {
                backValue = backValue.Substring(0, backValue.Length - 1);
                Console.Write("\b \b");
            }
        } while (inputKey.Key != ConsoleKey.Enter); //Loop until Enter key not pressed

        if (double.TryParse(backValue, out value))
            Console.Write("\n{0}^2 = {1}", value, Math.Pow(value, 2));

        Console.ReadKey();
    }

    static void Write()
    {
        backValue += inputKey.KeyChar;
        Console.Write(inputKey.KeyChar);
    }
}
Ovidzikas
  • 113
  • 11
0

You can do it with a single line code as follows:

int n;
Console.WriteLine("Enter a number: ");
while (!int.TryParse(Console.ReadLine(), out n)) Console.WriteLine("Integers only allowed."); // This line will do the trick
Console.WriteLine($"The number is {n}");

You can change int into double in case you wanted to allow double instead of integers and so on.

Zalanta7
  • 11
  • 1
  • 2
-1
        string input;
        double price;
        bool result = false;

        while ( result == false )
            {
            Console.Write ("\n Enter the cost of the item : ");
            input = Console.ReadLine ();
            result = double.TryParse (input, out price);
            if ( result == false )
                {
                Console.Write ("\n Please Enter Numbers Only.");
                }
            else
                {
                Console.Write ("\n cost of the item : {0} \n ", price);
                break;
                }
            }
  • *I want the keyboard buttons, A-Z, brackets, question mark, etc to be disabled. I want it so if you type it in, it will not show up in the Console. I only want the numbers 1-9 to show up.* This does none of those things. – Rawling Aug 11 '15 at 06:59