简体   繁体   中英

Restricting user to NOT input decimal

Hi I'm new in C# i just want to ask if this is possible? How to not allow the user to input decimal in console app in c#

I don't know a method to restrict the user from entering some characters in the console, but I have a mechanism for you to overcome the issues that you are facing.

You can make use of .TryParse() method of the type you are dealing with. The TryParse Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded. you can depend on that return value to check for valid inputs.

If you have to consider culture-specific conversion, you can make use of the overloaded method which accepts NumberStyles and IFormatProvider

Consider that you are dealing with integers, then your code will be like the following:

string inputStr="12.36";
int convertedValue=0;
if(int.TryParse(inputStr,out convertedValue))
{
    Console.WriteLine("Thanks for correct input");
    // proceed with your code with the converted value in convertedValue
}
else
{
   Console.WriteLine("Wrong input");
}

You can either use Console.ReadLine to read a whole line or Console.ReadKey to get single key strokes.

Using Console.ReadLine gives you every character, the user enters before pressing return. You have no control, what characters the users enters.

If you implement an user interaction using Console.ReadKey you can ignore every character the user is not allowed to type in and put a string together using all the characters you get.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM