Reading two Characters in C#

*爱你&永不变心* 提交于 2019-12-12 14:30:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!