Reputation: 61
I've been trying to figure this out for dozens of tries, but I can't seem to understand why this line executes?
Console.WriteLine("please enter a number.");
I get it on the screen even before I enter any character as input. any help is appreciated
int numberAsInt;
while (true) {
try {
numberAsInt = Convert.ToInt32(Console.ReadLine());
break;
}
catch {
Console.WriteLine("please enter a number.");
}
}
Upvotes: 3
Views: 154
Reputation: 5281
To piggyback on Emerson Chen's answer, the reason why is because Console.Readline will pull back information from the Console... which runs outside of your code logic.
This means that it doesn't wait until you type Console.Readline()
to get input. Sound like it shouldn't happen in a synchronous bit of code? Well, think of it this way: the console goes on working whether you tell it to or not.
Here's a quick example of something that could go wrong. You write a message to the console telling the user to keep hands away from the keyboard:
Console.WriteLine("Please don't type anything for 2 seconds.");
Good. Now that the user isn't going to mess up anything, you can do your work for 2 seconds, expecting no user input:
var startTime = DateTime.Now;
while (DateTime.Now < startTime.AddSeconds(2)) ;
Okay, now we're ready for some input:
Console.WriteLine("Please enter a value.");
var inputVal = Console.ReadLine();
Console.WriteLine("The value entered was: " + inputVal);
Works great. But wait, what if Johnny User ignores the warning, and types "100" then hits the "Enter" key before 2 seconds is elapsed? In that case, it is all recorded by the Console, and dutifully passed to Console.ReadLine()
when that line of code is reached... after the input has occurred from the user.
Upvotes: 1
Reputation: 1582
No need of an infinite while
loop and a try/catch
block to verify if the user entered a valid number, you can use int.TryParse()
instead.
int num;
string input = "";
while (!int.TryParse(input, out num))
{
Console.Write("Enter a number:");
input = Console.ReadLine();
}
Console.WriteLine("Number entered:" + num);
Upvotes: 1
Reputation: 822
You should not use try/catch to check your input. Better way:
int numberAsInt;
while (true) {
String str = Console.ReadLine();
if (int.TryParse(str, out numberAsInt)) {
break;
}
Console.WriteLine("please enter a number.");
}
Upvotes: 1
Reputation: 86
The reason the catch block fired is that there is an exception caused by:
Convert.ToInt32(Console.ReadLine())
The ReadLine()
method will read whatever you have already entered -- even if there is nothing. From MSDN:
[Returns] the next line of characters from the input stream, or null if no more lines are available.
If the standard input device is the keyboard, the ReadLine method blocks until the user presses the Enter key.
Upvotes: 3