Reputation: 23
Bear in mind I am new to C#.
I wish to check if a user's input has more than just one character. Specifically, I wish to ask the user for a Y/N, but if they type "yes" or "no" (or null) to ask them again.
What I have at the moment:
char guess;
Console.WriteLine("Please enter a letter");
guess = Convert.ToChar(Console.ReadLine());
This works well for if the user follows the instructions, but if more than one character is entered, or Enter is pressed, the "Convert.ToChar" fails.
Upvotes: 0
Views: 2972
Reputation: 21
Use a greater then or less then statement on that.
string input = Console.ReadLine();
if(input.Length > 1) { Console.WriteLine("Message"); Console.ReadLine(); } // If its bigger then 1
else { /* if it is one letter do code here */ }
Upvotes: 0
Reputation: 26454
I'd still prefer ReadLine()
over Read()
, it's more natural for user to press Enter
after they are done typing. With Read()
approach you'd have to handle Backspace
as well, so it gets more complicated. Suggesting something along these lines:
Console.WriteLine("Please enter a letter");
string input;
while(true)
{
input = Console.ReadLine();
if (input.Length == 1) { break; }
Console.WriteLine("Invalid input");
}
char guess = input[0];
Notice in the above you can easily add more validation, such as 0-9 not being a letter.
Upvotes: 1
Reputation: 191058
Why don't you do Console.ReadKey()
or Console.Read()
?
.Read
reads the next char off the buffer.
Upvotes: 8