+ 1

How can i make user input only numbers on console c#

I need way to make user only input numbers on my program

2nd Mar 2017, 11:48 PM
El missouri
El missouri - avatar
2 Antworten
+ 17
You can't force a user to enter only numbers. You can take the users' input as a string and try to change it to a number. For example: string input = Console.ReadLine(); int number = int.Parse(input); If the user inputs "42", input will be "42" and number will be 42. int.Parse() will throw an exception if the string cannot be parsed. So have a try-catch ready (or use int.TryParse()). You could make a while loop which will continue to loop until a valid input is entered 😎 Good luck 🍰
3rd Mar 2017, 12:18 AM
Jafca
Jafca - avatar
+ 2
I agree with the previews answer. One more alternative is to show a message saying: Console.WriteLine("Please type only numbers"); Console.ReadLine(x);
3rd Mar 2017, 3:15 AM
Corrina Galetza