【问题标题】:Check the pressed key and and add it to String检查按下的键并将其添加到字符串
【发布时间】:2017-04-10 16:09:13
【问题描述】:

我正在编码,但我遇到了 c# 问题。我有以下代码:

    if (Console.ReadKey(true).KeyChar.ToString() == "l") // Reading single key in console
            goto load; 
// If not, continue

// Here, if I didn't press "l", I have to press the key once more, because at first, it checked it in if statement above so it is reding this into the string on the second time. So just want that if I didn't press "l" Automatically add that key to string below
            string read = Console.ReadLine();

问题是,如果我不想按“l”的第一个字母,我必须按其他的 2 次。 (因为第一次按下正在检查 Console.ReadKey()。) 那么,如果我按下与“l”不同的键,我该如何做到这一点,它会自动将其写入下面的 Console.ReadLine?谢谢

【问题讨论】:

  • 如果您的代码中有goto,您将遇到更多问题
  • @UnholySheep 已经告诉他/她了,但是....
  • 避免使用goto 语句,您可以改用if
  • 我删除了那个标签并转到这里,这也是同样的问题。
  • 忠告,DON'T use GOTO Statements\

标签: c# string console


【解决方案1】:

执行此操作的一种方法是将第一个字符捕获到一个变量中,这样您就可以将其保存以备后用,以防它不是您要查找的那个。另外,请注意,如果我们希望输出显示在控制台窗口上,我们不会将 true 传递给 ReadKey() 方法。

如果输入的不是你要找的那个,那么你可以把Console.ReadLine()的结果保存到另一个变量中,并把原来的字符加到它的开头:

// First capture the character into a variable, so we can save it for later
var firstChar = Console.ReadKey().KeyChar.ToString();

if (firstChar == "l")
{
    // Do something here, or call another method,
    // But don't GOTO anywhere.
    Console.WriteLine("You pressed 'l'");
}
else
{
    // If they didn't press 'L', then we take the saved character and
    // Add it to the beginning of the rest of the user input:
    var restOfInput = firstChar + Console.ReadLine();

    Console.WriteLine($"You entered the text: {restOfInput}");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多