Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an integer from console input

Tags:

c#

I'm trying to get an integer from user input. I used the following

int locationX = Convert.ToInt32(Console.Read());
myObject.testFunction(locationX);

and got an unexpected error related to my testFunction. I used the debugger and found that when I input the number 2 into console - locationX becomes 50. What is going on here and how can I get locationX to match the user input?

like image 498
user2202911 Avatar asked Mar 19 '26 16:03

user2202911


1 Answers

You should read the input typed by the user when he/she presses the enter key.
This is done using Console.ReadLine. But you have a problem in the following Convert.ToInt32. If the user doesn't type something that could be converted to an integer your code will crash.

The correct method to read an integer from the console is

int intValue;
string input = Console.ReadLine();
if(Int32.TryParse(input, out intValue))
    Console.WriteLine("Correct number typed");
else
    Console.WriteLine("The input is not a valid integer");

The Int32.TryParse method will try to convert the input string to a valid integer. If the conversion is possible then it will set the integer passed via out parameter and returns true. Otherwise, the integer passed will be set to the default value for integers (zero) and the method returns false.

TryParse doesn't throw an expensive exception like Convert.ToInt32 or the simple Int.Parse methods

like image 190
Steve Avatar answered Mar 22 '26 06:03

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!