2

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?

2
  • What is myObject.testFuction? Commented Nov 24, 2013 at 18:52
  • Its just a dummy function, the variable locationX is 50 before its called. Commented Nov 24, 2013 at 18:54

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

4

You need to use Console.ReadLine().

Console.Read() reads the next character from the console input stream, not the entire line, which explains why you're getting a weird result.

Comments

3

Use Console.ReadLine() instead of Console.Read() -

int locationX = Convert.ToInt32(Console.ReadLine());

Comments

2

Don't read the console input until the user hits ENTER.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.