why getting null value from console in c# for readLine() after using read()

后端 未结 1 946
南笙
南笙 2020-12-21 07:42

I have the following code

char c1 = (char)Console.Read();
Console.WriteLine(\"Enter a string.\");
string instr = Console.ReadLine();

It tak

相关标签:
1条回答
  • 2020-12-21 08:06

    When you call Read(), it still blocks until you hit enter even though the actual method will only consume a single character from the input stream. When you subsequently hit enter, the character is indeed read, but the newline isn't. Since the newline is still in the input stream, the call to ReadLine() immediately returns, as it's read a line terminator. You can see this behaviour in more depth if you were to debug.

    To resolve this I could suggest the following, using ReadKey():

    char c1 = Console.ReadKey().KeyChar;
    Console.WriteLine(Environment.NewLine /* Added simply for readability */
        + "Enter a string.");
    string instr = Console.ReadLine();
    

    If you would like the user to still hit enter after the Read(), just use ReadLine and take a substring for the first character.

    0 讨论(0)
提交回复
热议问题