问题描述
我一直在尝试在C#中使用Console.Read()和Console.ReadLine(),但结果却很奇怪。例如,这段代码
I have been trying to use Console.Read() and Console.ReadLine() in C# but have been getting weird results. for example this code
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);
}
当我输入1的数字时,一直给我的金额= 49学生,我什至没有机会输入学生姓名。
has been giving me that amount = 49 when I input 1 for the number of students, and Im not even getting a chance to input a student name.
推荐答案
这是因为您读取了一个字符。
使用诸如 ReadInt32()
之类的适当方法,该方法可确保从读取符号到所需类型的正确转换。
This because you read a char.Use appropriate methods like ReadInt32()
that takes care of a correct conversion from the read symbol to the type you wish.
得到 49
的原因是因为它是'1'符号的字符代码,而 not 是整数表示形式。
The reason why you get 49
is because it's a char code of the '1' symbol, and not it's integer representation.
char code
0 : 48
1 : 49
2: 50
...
9: 57
例如: ReadInt32 ()
如下所示:
public static int ReadInt32(string value){
int val = -1;
if(!int.TryParse(value, out val))
return -1;
return val;
}
并像这样使用:
int val = ReadInt32(Console.ReadLine());
能够创建扩展方法<
,但是很遗憾,无法在静态类型和是静态
类型。
It Would be really nice to have a possibility to create an extension method
, but unfortunately it's not possible to create extension method on static type and Console is a static
type.
这篇关于Console.Read()和Console.ReadLine()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!