英文:
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。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论