2

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?

Mr_Green
  • 40,727
  • 45
  • 159
  • 271

4 Answers4

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))
{
}
Habib
  • 219,104
  • 29
  • 407
  • 436
  • 3
    sidenote, difference between parse/tryparse/convert is explained here: http://stackoverflow.com/questions/199470/whats-the-main-difference-between-int-parse-and-convert-toint32 – Mike Trusov Nov 16 '12 at 05:13
4

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);
lc.
  • 113,939
  • 20
  • 158
  • 187
2

You need Convert.ToInt32(string),

int res = Convert.ToInt32(yourcharvar.ToString());
Adil
  • 146,340
  • 25
  • 209
  • 204
1

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");    
Mr_Green
  • 40,727
  • 45
  • 159
  • 271