Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Conversions from string to int

Status
Not open for further replies.

Larsson

Programmer
Jan 31, 2002
140
SE
Hi!

I am an old C++ programmer and I have tried and treid again, but I can't understand how I convert a string or char to an integer.

int i;
string k = "123";
char j = "3";

i = j; //This gives hexa (I think) for 3: 51
i = (int) j; //Something.
i = (int) k; //Doesn't work.

Is there a function that does this, or do I have to write one myself?

Thanks for all help, Larsson.
 
You can always use the inbuilt functions "atoi" and "atof".
Right at this moment I can not recall in which library you will find them, but indeed these functions are there.
I did use them long ago for a program.
 
Larsson -

Ignore AbyBaby's post - atoi and atof are old C-style conversion functions and they're not in .NET.

What you want is to use the static methods (no need to instantiate a copy first) of the Convert class. There's an overload of the ToInt32() method available for converting from a String:
Code:
   String MyStringValue = "46";

   int MyIntValue = Convert.ToInt32(MyStringValue);

You shouldn't need to set a reference to gain access to the Convert class, as it's part of the System namespace (which the project wizard includes in almost every new project).

Chip H.
 
another solution is:

i = int.Parse(string)

Happy Coding!
 
I would have figure out the Convert class myself, but thanks for all help anyway.

Larsson
 
Alcar -
I forgot about the Parse method - I'm always forgetting that the int datatype in C# is really a System.Int32 value type (ie. a struct) that has methods on it.

Thanks for the alternate method!

Chip H.
 
how would I do the following in C#:

C:

char *a = "123wow";
int i = atoi(a);

if (i == 123)
{
// This be good!
}

 
String a = "123wow";
int i = int.Parse(a);
if (i == 123) {
// This be good
}

Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top