输入字符时Convert.ToInt32(Readline())给出错误 [英] Convert.ToInt32(Readline()) gives error when a character is entered

查看:251
本文介绍了输入字符时Convert.ToInt32(Readline())给出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看下面的代码

Hi, Look at the Following code

char c = 'a';
a=Convert.ToInt32(c);
Console.WriteLine("hi" + a);//displays output:- Hi97
a=Convert.ToInt32(Console.ReadLine());//Gives complie time error(throws an exception) if I enter 'a'(a only without quotes) on screen.


为什么Convert.ToInt32()在两种情况下的行为会有所不同.


Why the Convert.ToInt32() is behaving differently in 2 situations.

推荐答案

在第一种情况下,您定义了一个字符,添加后将其转换为ascii值(97)到字符串.

当您使用Console.ReadLine()方法时,该方法不返回字符而是字符串.因此,如果此字符串包含字符,则无法将其转换为整数.
In the first case you have defined a single character which is converted to ascii value (97) when added to the string.

When you use Console.ReadLine() method, the method doesn''t return a character but a string. So this string cannot be converted to integer if it contains characters.


请参见^


因为在ASCII字符集中"a"的等效项是97.在这种情况下,使用Int32.TryParse方法会更好.请参阅链接以供参考:
http://msdn.microsoft.com/en-us/library/f02979c7.aspx [ ^ ]

问候,
爱德华
Because the equivalent of ''a'' in ASCII character set is 97. Using Int32.TryParse method would be better in this case. See the link for your reference:
http://msdn.microsoft.com/en-us/library/f02979c7.aspx[^]

Regards,
Eduard


这篇关于输入字符时Convert.ToInt32(Readline())给出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆