2013-05-01 105 views
1
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; 
} 

我曾嘗試輸入這些:到Console.ReadLine()跳過第一個輸入字符

  • Ÿ - >它給了我一個空字符串,
  • Y(空格+ Y) - >它給我的「Y」

我已經檢查了其他類似的帖子,但沒有一個解決我的問題。 ReadLine()仍跳過第一個輸入字符。

UPDATE已解決,see below

+1

請檢查這個職位。它會解釋你的問題 http://stackoverflow.com/questions/3800343/c-sharp-why-is-it-skipping-my-console-readline – Driftware 2013-05-01 05:13:22

+1

我在Ideone.com試過這個,並沒有問題(http://ideone.com/1MSBMb)。你使用的是什麼版本的.NET? – Jetti 2013-05-01 05:14:30

+2

其他讀者注意:從@ Franva的回答下面,似乎這個問題是不完整的... – 2013-05-01 07:48:50

回答

1

謝謝大家回覆我的帖子。

這是我的壞,不考慮我的代碼中的多線程功能。我會盡力解釋我錯在哪裏,以便對所有的答覆表示感謝。

BackgroundWorker worker = .....; 
    public static void Main(string[] args) 
    { 
     InitWorker(); 
     Console.Read(); 
    } 

public static void InitWorker() 
{ 
    .... 
    worker.RunWorkerAsync(); 
} 


static void worker_DoWork(....) 
{ 
    .....this is where I wrote the code... 
} 

問題是我開始了一個與主機線程異步運行的子線程。當子線程跑到這一行時:var answer = Console.ReadLine();主機線程運行到Console.Read();與此同時。 所以發生了什麼,它看起來像我輸入一個字符爲var answer = Console.ReadLine(),但它實際上餵給主機線程上運行的Console.Read(),然後它是轉線程ReadLine()。當子線程從鍵盤獲得輸入時,第一個輸入的字符已經被主機線程佔用,然後整個程序完成並關閉。

我希望我的解釋清楚。

+1

現在有道理。我相信你可以使用'Application.Run()'來防止在main的結尾退出。 – SimpleVar 2013-05-01 07:50:39

0

基本上你需要改變Console.Read - >到Console.ReadLine

+0

我使用ReadLine()。 – Franva 2013-05-01 06:20:34

+0

我也編譯了你的代碼並對它進行了測試,得到了與我輸入相同的值,並且我在Linux機器上使用了Mono。 – Driftware 2013-05-01 06:36:19

+1

很高興解決。我有點擔心,想知道爲什麼你的原始代碼可以工作。Yah Good'ol Threading :) – Driftware 2013-05-01 06:42:25

1

建議的調整:

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

要點:

1)一個字符串可能是控制檯的最簡單的類型輸入以處理

2)控制檯輸入是面向行的 - 在輸入可用於程序之前,您必須鍵入「Enter」。

+0

這與發佈的內容有什麼不同?你所做的一切都是明確地輸入變量。 – 2013-05-15 07:59:17