输出文本的第一个字母会在后续迭代中消失。

huangapple go评论59阅读模式
英文:

The first letter of the output text disappears with subsequent iterations

问题

请帮助我弄清楚为什么在第2次及后续迭代后,输出文本的第一个字母消失。

public static void Main()
{
  OutputEncoding = Encoding.UTF8;

  int playersNumber = 0;
  string? name;
  while (true)
  {
    Console.Write($"请输入您的姓名,玩家 #{playersNumber}: ");
    string possibleName = Console.ReadLine();

    Console.WriteLine();
    Console.WriteLine("您确认您的选择吗?");
    Console.WriteLine();
    Console.WriteLine("按 ENTER 确认");
    Console.WriteLine("按 ESC 重新输入");

    char choice = (char)Console.ReadKey().Key;

    if (choice == (char)ConsoleKey.Enter)
    {
      name = possibleName;
      return;
    }
    if (choice == (char)ConsoleKey.Escape)
    {
      continue;
    }
  }
}

输出文本的第一个字母会在后续迭代中消失。

英文:

Please help me figure out why the first letter of the output text disappears after the 2nd and subsequent iterations

public static void Main()
{
  OutputEncoding = Encoding.UTF8;

  int playersNumber = 0;
  string? name;
  while (true)
  {
    Console.Write($"Write your name, player #{playersNumber}: ");
    string possibleName = Console.ReadLine();

    Console.WriteLine();
    Console.WriteLine("You confirm your choice?");
    Console.WriteLine();
    Console.WriteLine("press ENTER for YES");
    Console.WriteLine("press ESC for REWRITE");

    char choice = (char)Console.ReadKey().Key;

    if (choice == (char)ConsoleKey.Enter)
    {
      name = possibleName;
      return;
    }
    if (choice == (char)ConsoleKey.Escape)
    {
      continue;
    }
  }
}

输出文本的第一个字母会在后续迭代中消失。

答案1

得分: 3

这是因为当你按下 esc 键时,它也会输入到 cmd 中。因此,它最终成为下一个打印的字符串中的第一个字符。

所以你的选择行应该像这样,以捕获 esc 键的按下。

char choice = (char)Console.ReadKey(true).Key;

ReadKey 作为一个重载,传入一个名为 intercept 的布尔值。

参数
intercept (bool) 确定是否在控制台窗口中显示按下的键。true 表示不显示按下的键;否则为 false。

Microsoft Docs For ReadKey

英文:

This is a happening because when you press esc you are also typing it into the cmd. So it ends up esc the first char in the next printed string.

so your choice line should look like this to capture the esc press.

char choice = (char)Console.ReadKey(true).Key;

ReadKey as an override passing in a bool called intercept.

> Parameters
> intercept (bool) Determines whether to display the pressed
> key in the console window. true to not display the pressed key;
> otherwise, false.

Microsoft Docs For ReadKey

huangapple
  • 本文由 发表于 2023年2月27日 06:58:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定