Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to Integer [duplicate]

Tags:

string

c#

Possible Duplicate:
how can I convert String to Int ?

Hi,

I have the following problem converting string to an integer:

string str = line.Substring(0,1);

//This picks an integer at offset 0 from string 'line' 

So now string str contains a single integer in it. I am doing the following:

int i = Convert.ToInt32(str);

i should be printing an integer if I write the following statement right?

Console.WriteLine(i);

It compiles without any error but gives the following error on runtime:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Input string was not in a correct format.

Any help please?

like image 716
zack Avatar asked Aug 20 '09 04:08

zack


1 Answers

Rather than using Convert.ToInt32(string) you should consider using Int32.TryParse(string, out int) instead. The TryParse methods are there to help deal with user-provided input in a safer manner. The most likely cause of your error is that the substring you are returning has an invalid string representation of an integer value.

string str = line.Substring(0,1);
int i = -1;
if (Int32.TryParse(str, out i))
{
   Console.WriteLine(i);
}
like image 101
Scott Dorman Avatar answered Oct 04 '22 00:10

Scott Dorman