我一直在尝试在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);
}当我输入1作为学生人数时,我已经给了我这个数字= 49,而我甚至没有机会输入学生的名字。
发布于 2012-09-07 04:48:01
这是因为你读了一个字符。使用适当的方法,如ReadInt32(),它负责将读取的符号正确转换为您想要的类型。
你得到49的原因是因为它是'1‘符号的字符代码,而不是整数表示。
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());如果有可能创建一个extension method就太好了,但不幸的是无法在静态类型上创建扩展方法,而Console是一个static类型。
发布于 2012-09-07 04:50:38
试着这样修改你的代码
int amount;
while(true)
{
Console.WriteLine("How many students would you like to enter?");
string number = Console.ReadLine();
if(Int32.TryParse(number, out amount))
break;
}
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);
} 相反,要使用Read,请使用ReadLine,然后使用Int32.TryParse检查用户输入是否真的是一个整数。如果用户没有输入有效的数字,请重复该问题。
使用Console.Read会将您的输入限制为单个字符,需要对其进行转换并检查为有效数字。
当然,这是一个残酷的例子,没有任何错误检查或任何类型的安全中止循环。
发布于 2016-02-03 09:50:22
对于可能仍然需要这个的人:
static void Main(string[] args)
{
Console.WriteLine("How many students would you like to enter?");
var amount = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} {1}", "amount equals", amount);
for (int i = 0; i < amt; i++)
{
Console.WriteLine("Input the name of a student");
String StudentName = Console.ReadLine();
Console.WriteLine("the Students name is " + StudentName);
}
}https://stackoverflow.com/questions/12308098
复制相似问题