Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Char into int after read from a file

Tags:

c#

char

file-io

int

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?

like image 653
Mark Van Duyne Avatar asked Dec 10 '25 13:12

Mark Van Duyne


2 Answers

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))
{
}
like image 191
Habib Avatar answered Dec 12 '25 02:12

Habib


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);
like image 25
lc. Avatar answered Dec 12 '25 03:12

lc.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!