首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Console.Read()和Console.ReadLine()问题

Console.Read()和Console.ReadLine()问题
EN

Stack Overflow用户
提问于 2012-09-07 04:45:56
回答 9查看 51.4K关注 0票数 6

我一直在尝试在C#中使用Console.Read()和Console.ReadLine(),但得到了奇怪的结果。例如,下面的代码

代码语言:javascript
复制
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,而我甚至没有机会输入学生的名字。

EN

回答 9

Stack Overflow用户

发布于 2012-09-07 04:48:01

这是因为你读了一个字符。使用适当的方法,如ReadInt32(),它负责将读取的符号正确转换为您想要的类型。

你得到49的原因是因为它是'1‘符号的字符代码,而不是整数表示。

代码语言:javascript
复制
char     code
0 :      48
1 :      49
2:       50
...
9:       57

例如:ReadInt32()可能如下所示:

代码语言:javascript
复制
public static int ReadInt32(string value){
      int val = -1;
      if(!int.TryParse(value, out val))
          return -1;
      return val;
}

并像这样使用它:

代码语言:javascript
复制
int val = ReadInt32(Console.ReadLine());

如果有可能创建一个extension method就太好了,但不幸的是无法在静态类型上创建扩展方法,而Console是一个static类型。

票数 11
EN

Stack Overflow用户

发布于 2012-09-07 04:50:38

试着这样修改你的代码

代码语言:javascript
复制
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会将您的输入限制为单个字符,需要对其进行转换并检查为有效数字。

当然,这是一个残酷的例子,没有任何错误检查或任何类型的安全中止循环。

票数 3
EN

Stack Overflow用户

发布于 2016-02-03 09:50:22

对于可能仍然需要这个的人:

代码语言:javascript
复制
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);
     }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12308098

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档