简体   繁体   English

为什么在输入新的char值后while循环关闭

[英]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.

相关问题 C# 控制台:在 char 变量中输入变量后,如何在 LastName 中输入值? - C# Console : How can i enter a value in LastName after i Enter a variable in the char variable? 希望我的 while 循环在我输入一个超过 800 的数字后完成并输出,但它给了我未处理的异常 - Want my while loop to finish and output after I enter a number which is over 800 but it is giving me unhandled exceptions 如何在 while 循环中使用“char”作为标记值 - How do you use a “char” as a sentinel value in a while loop 为什么我必须在循环中两次输入度数? - Why do I have to enter the degrees twice in the loop? 为什么Split(new char ['\\\\'])不能按我的想法工作 - Why Split(new char['\\']) not work as what I think 为什么我可以在while循环之前更改构造的链接列表,但之后不能更改呢? - c# - Why can I alter my constructed link list before a while loop, but not after it? 在 C# 中,我输入一个字符,然后输出一些东西。 但是在输入控制后不等待输入并直接给出输出 - In C# I am taking a char input and then I output something. But after input control is not waiting for enter and straightaway giving output (Char)174返回(Char)0174的值,为什么? - (Char)174 returning the value of (Char)0174, why? 输入无效后,如何获取代码以重新进入循环 - How do I get my code to re-enter the loop after an invalid input 输入新数据后,如何在datagridview中刷新数据 - How can i refresh my data in datagridview after in enter new data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM