[英]Why while loop closes after I enter new char value
Even if I enter the y value to be 'y', loop still closes. 即使我将y值输入为“ y”,循环仍会关闭。 If I enter the value 'y', then it asks "Do you want to continue? Press y" and loop closes without asking to enter new y value.
如果输入值“ y”,则询问“是否要继续?按y”,然后循环关闭而不要求输入新的y值。
char y = 'y';
while (y == 'y')
{
Console.WriteLine("Do you want to continue? Press y");
y = (char)Console.Read(); //here the problem starts
}
The Console.Read() blocks waiting for the input and terminates by pressing the enter key which appends a carriage return which is what it will read next time through the loop.This is one example of why Read() is not the best option when you need to redirect flow based on user input,instead you have other options: Console.Read()阻止等待输入,并按Enter键终止,该键附加回车符,这将是下一次在循环中读取的内容。这是为什么Read()不是最佳选择的一个示例您需要根据用户输入来重定向流程,而您还有其他选择:
First:Consume the rest of the input buffer by placing a readline after like this: 首先:通过在此之后放置一条readline来消耗其余的输入缓冲区:
char y = 'y';
while (y == 'y')
{
char temp;
Console.WriteLine("Do you want to continue? Press y");
y = (char)Console.Read();
Console.ReadLine();
}
Second: Simply replace Read() for ReadLine() altering the char to a string or if you want to keep the char like this: 第二:只需将Read()替换为ReadLine()即可,将char更改为字符串,或者如果您希望保留char像这样:
y = (char)Console.ReadLine()[0];
Third:Using ReadKey(): 第三:使用ReadKey():
ConsoleKeyInfo key = Console.ReadKey();
y = key.KeyChar;
Console.WriteLine();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.