2016-12-02 28 views
0

這是一個非常簡單的代碼。但這是我第一次用C#編寫控制檯應用程序。簡單地說,使用這兩條線Console.Read在C#中的失敗

int iRoll; 
    Console.WriteLine("Roll Dice and input number for your move"); 
    iRoll = Console.Read(); 

,如果我進入5號從cmd窗口(如果是從數字鍵盤或鍵盤也沒關係),用於iRoll的值是53。爲什麼是這樣?

+1

'int.TryParse(Console.ReadLine(),out iRoll);' – mybirthname

回答

9

Console.Read返回包含從輸入流中讀取的字符的int

string line = Console.ReadLine(); 

可以使用int.TryParse然後解析串入一個int:

int iRoll; 
if (int.TryParse(line, out iRoll)) { 
    // use iRoll 
} else { 
    // handle invalid input 
} 
如果你想包含行的字符串,你應該使用 ReadLine代替字符 5被編碼爲53

+0

這太容易修復和重複了。誰動了我的動議刪除它? – xarzu

1

這是因爲你讀了'5'字符的ASCII碼。這是53值。

0

您可能需要使用

Console.ReadLine(); 

相反。並創建一個例外,所以它只接受整數。