2017-04-10 6 views
-3

私はコーディングしていますが、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に書き込まれます。ありがとう

+5

お持ちの場合は、 '後藤'あなたのコードでは、もっと多くの問題があるようになっています – UnholySheep

+0

@UnholySheepは既に彼に言いましたが、.... – Steve

+0

の代わりに' goto'ステートメントを使わないでください。 –

答えて

1

これを行う1つの方法は、変数に最初の文字をキャプチャすることです。それで、探している文字でない場合は後で保存することができます。また、出力をコンソールウィンドウに表示する場合は、trueReadKey()メソッドに渡しません。

入力は、あなたが別の変数に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}"); 
} 
+0

ありがとうございます:) – Jacob

関連する問題