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

大憨熊 提交于 2019-12-18 08:58:57

问题


I have the following code

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

It takes a value for c1, after that it prints "Enter a string". However when I try to enter a string, it appears to be working like ReadKey(), meaning that as soon as I press any key it's showing that instr has a null value.

If I remove the first line (char c1 = (char)Console.Read();), program works correctly.

Why is this?


回答1:


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.



来源:https://stackoverflow.com/questions/17781109/why-getting-null-value-from-console-in-c-sharp-for-readline-after-using-read

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