问题
I cannot read a second character with Console.Read() method. I mean I don't get any Prompt to read the second character from Keyboard. Any help please? Also, I understand that character is by default an int but we still need to convert it to char when reading from input, is it right? The code below reads the first char but terminates with the second.
public static void Main()
{
Console.WriteLine("The First Character?:");
char firstChar=Convert.ToChar(Console.Read());
Console.WriteLine("The Second Character?:");
char secondChar=Convert.ToChar(Console.Read());
}
回答1:
Please see Console.Read. Specifically, this part:
The Read method blocks its return while you type input characters; it terminates when you press the Enter key. Pressing Enter appends a platform-dependent line termination sequence to your input (for example, Windows appends a carriage return-linefeed sequence). Subsequent calls to the Read method retrieve your input one character at a time. After the final character is retrieved, Read blocks its return again and the cycle repeats.
回答2:
Looks like Console.ReadKey()
is what you actually want.
回答3:
Perhaps this code is closer to what you're looking for...
public static void Main()
{
Console.WriteLine("The First Character?:");
char firstChar = Convert.ToChar(Console.ReadKey().KeyChar);
Console.WriteLine();
Console.WriteLine("The Second Character?:");
char secondChar = Convert.ToChar(Console.ReadKey().KeyChar);
}
回答4:
Your second Console.Read()
is consuming the carriage return terminating the first read.
Console.ReadKey
is a bit friendlier to use, since it doesn't require a terminating carriage return. If you want to continue using Console.Read
, you might try consuming and discarding the carriage return before the second prompt, like:
public static void Main()
{
Console.WriteLine("The First Character?:");
char firstChar = Convert.ToChar(Console.Read());
Console.Read(); // consume carriage return
Console.WriteLine("The Second Character?:");
char secondChar = Convert.ToChar(Console.Read());
Console.WriteLine(secondChar);
}
来源:https://stackoverflow.com/questions/5162670/reading-two-characters-in-c-sharp