c# - Console.ReadLine() 跳过第一个输入字符

标签 c#

Console.WriteLine("You have not installed Microsoft SQL Server 2008 R2, do you want to install it now? (Y/N): ");
//var answerKey = Console.ReadKey();
//var answer = answerKey.Key;
var answer = Console.ReadLine();
Console.WriteLine("After key pressed.");
Console.WriteLine("Before checking the pressed key.");

//if(answer == ConsoleKey.N || answer != ConsoleKey.Y)
if (string.IsNullOrEmpty(answer) || string.IsNullOrEmpty(answer.Trim()) || string.Compare(answer.Trim(), "N", true) == 0)
{
    Console.WriteLine("The installation can not proceed.");
    Console.Read();
    return;
}

我尝试输入这些:

  • y -> 它给了我一个空字符串,
  • y(whitespace+y) -> 它给了我“y”

我检查了其他类似的帖子,但没有一个能解决我的问题。 ReadLine() 仍然会跳过第一个输入字符。

更新已解决,see below .

最佳答案

建议更改:

Console.Write("Enter some text: ");
String response = Console.ReadLine();
Console.WriteLine("You entered: " + response + ".");

要点:

1) 字符串可能是最容易处理的控制台输入类型

2) 控制台输入是面向行的 - 在输入可供程序使用之前,您必须键入“Enter”。

关于c# - Console.ReadLine() 跳过第一个输入字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16313042/

相关文章:

c# - 如何从 C# 中的 Shapefile 导出 WKT?

c# - ObjectListView 嵌套对象

c# - 使用 linq 将字典值转换为列表

c# - 如何测试用户对数据库的权限

c# - 是否可以使用MySql赋值运算符(:=) in a MySqlCommand?

c# - WPF 突出显示验证失败的选项卡标题

c# - 对于明显有效的格式,TimeSpan.ParseExact() 返回 false

c# - Elasticsearch Nest-搜索动态数据

c# - 哪个内存分析器会告诉我每一代都收集了什么?

c# - 在 WPF 中解析本地 XML 文档(调试工作,发布后失败)