简体   繁体   中英

Converting Char into int after read from a file

I am reading from a text file and I have a value that is read from the text file that I want to store as an int . I am doing this in c#. For example I read in 4 from the file but as a char it is 4 but if I just cast it to an int it takes the value 52, I think. How do I take that char value 4 and store it as an int as a 4?

Convert your character to string and then you can use int.Parse , int.TryParse , Convert.Int32(string) to convert it to integer value.

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))
{
}

The easiest way is to just subtract out the value of '0' :

char c = '4';
int i = (int)(c - '0');

Or you could go through string instead:

char c = '4';
int i = int.Parse(c.ToString());

Note that if you have a string instead of a char, just do:

string value = "4";
int i = int.Parse(value);

你需要Convert.ToInt32(string)

int res = Convert.ToInt32(yourcharvar.ToString());

use TryParse always because it catches the exceptions if any.(It has inbuilt trycatch block)
In other words, it is Safe .

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");    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM