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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With