Mik*_*ell 6 .net c# console-application
我一直在尝试在C#中使用Console.Read()和Console.ReadLine(),但结果却很奇怪.例如这段代码
Console.WriteLine("How many students would you like to enter?");
int amount = Console.Read();
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i=0; i < amount; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
Run Code Online (Sandbox Code Playgroud)
当我输入1学生人数时,我已经给了我这个数额= 49,我甚至没有机会输入学生姓名.
Tig*_*ran 11
这是因为你读了一个char.使用适当的方法ReadInt32()来处理从读取符号到您希望的类型的正确转换.
你得到的原因49是因为它是'1'符号的char代码,而不是它的整数表示.
char code
0 : 48
1 : 49
2: 50
...
9: 57
Run Code Online (Sandbox Code Playgroud)
例如:ReadInt32()看起来像这样:
public static int ReadInt32(string value){
int val = -1;
if(!int.TryParse(value, out val))
return -1;
return val;
}
Run Code Online (Sandbox Code Playgroud)
并使用它像:
int val = ReadInt32(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)
有可能创建一个很好extension method,但不幸的是,无法在静态类型上创建扩展方法,而Console是一种static类型.
| 归档时间: |
|
| 查看次数: |
49995 次 |
| 最近记录: |