[英]C# streamreader Read(char[] buffer, int index, int count) method fails to read from file after streamreader object Position is greater than buffersize
[英]Converting Char into int after read from a file
我正在从一个文本文件中读取,并且我有一个从我想要存储为int
的文本文件中读取的值。 我在c#中这样做。 例如,我从文件中读取4,但作为char
它是4,但如果我只是将它转换为int
,我认为它取值52。 如何获取char值4并将其作为int
存储为4?
将您的字符转换为字符串 ,然后您可以使用int.Parse , int.TryParse , Convert.Int32(string)将其转换为整数值。
char ch = '4';
int val = Convert.ToInt32(ch.ToString());
// using int.Parse
int val2 = int.Parse(ch.ToString());
//using int.TryParse
int val3;
if(int.TryParse(ch.ToString(), out val3))
{
}
最简单的方法是减去'0'
的值:
char c = '4';
int i = (int)(c - '0');
或者你可以通过string
代替:
char c = '4';
int i = int.Parse(c.ToString());
请注意,如果您有一个字符串而不是char,只需执行以下操作:
string value = "4";
int i = int.Parse(value);
int res = Convert.ToInt32(yourcharvar.ToString());
始终使用TryParse
是因为它捕获了异常(如果有的话)。(它有内置的trycatch块)
换句话说,它是安全的 。
char foo = '4';
int bar;
if(int.TryParse(foo.ToString(), out bar)) //if converted returns TRUE else FALSE
Console.WriteLine(bar); //bar becomes 4
else
Console.WriteLine("The conversion is not possible");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.