【问题标题】:Why while loop closes after I enter new char value为什么我输入新的字符值后while循环关闭
【发布时间】:2014-08-18 00:55:37
【问题描述】:

即使我将 y 值输入为 'y',循环仍然会关闭。 如果我输入值 '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
         }

【问题讨论】:

  • 添加断点,从控制台读取后立即查看 y 的值是什么
  • 这在我的系统上运行(原样) - 让你继续
  • remark:在这种情况下,do ... while 更易读,恕我直言(您可以将 (char)Console.Read() == 'y' 插入 while-part

标签: c# while-loop char


【解决方案1】:

Console.Read() 阻塞等待输入并通过按回车键终止,该回车键附加一个回车符,这是它将在下一次循环中读取的内容。这是为什么 Read() 不是当您需要根据用户输入重定向流程时的最佳选择,而不是您有其他选择:

首先:通过在后面放置一个 readline 来消耗输入缓冲区的其余部分,如下所示:

char y = 'y';
while (y == 'y')
{
    char temp;
    Console.WriteLine("Do you want to continue? Press y");
    y = (char)Console.Read();
    Console.ReadLine();   
}

第二:只需将 Read() 替换为 ReadLine() 即可将字符更改为字符串,或者如果您想像这样保留字符:

y = (char)Console.ReadLine()[0];

第三:使用ReadKey():

ConsoleKeyInfo key = Console.ReadKey();
y = key.KeyChar;
Console.WriteLine();

【讨论】:

  • 如果问得不算多,能否请您解释一下第二个示例中的 [0] 是什么?我尝试 google,但 google 不搜索方括号。
  • 它是字符串的索引器,例如:string str = "test";字符 c = str[0];如果它是 [1],则 char c 将具有 't'。 c 将是 'e'。
猜你喜欢
  • 2011-02-07
  • 2019-03-12
  • 2017-06-26
  • 2017-09-16
  • 2018-04-30
  • 2016-07-27
  • 1970-01-01
  • 2020-05-11
  • 2015-12-25
相关资源
最近更新 更多