這是一個非常簡單的代碼。但這是我第一次用C#編寫控制檯應用程序。簡單地說,使用這兩條線Console.Read在C#中的失敗
int iRoll;
Console.WriteLine("Roll Dice and input number for your move");
iRoll = Console.Read();
,如果我進入5號從cmd窗口(如果是從數字鍵盤或鍵盤也沒關係),用於iRoll的值是53。爲什麼是這樣?
這是一個非常簡單的代碼。但這是我第一次用C#編寫控制檯應用程序。簡單地說,使用這兩條線Console.Read在C#中的失敗
int iRoll;
Console.WriteLine("Roll Dice and input number for your move");
iRoll = Console.Read();
,如果我進入5號從cmd窗口(如果是從數字鍵盤或鍵盤也沒關係),用於iRoll的值是53。爲什麼是這樣?
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
這太容易修復和重複了。誰動了我的動議刪除它? – xarzu
這是因爲你讀了'5'字符的ASCII碼。這是53值。
您可能需要使用
Console.ReadLine();
相反。並創建一個例外,所以它只接受整數。
'int.TryParse(Console.ReadLine(),out iRoll);' – mybirthname