这是一个非常简单的代码。但这是我第一次用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