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!

string to int conversion 1

Status
Not open for further replies.

qkslvrwolf

Programmer
Jul 9, 2002
28
US
Is there a fast, easy way to do string to int conversion in C? (C is driving me slowly insane, by the way).

Thanks!

sean
 
int main() {

char *str = "12345";
int number = atoi(char *str);
return 1;
}

There ya go. :)
Prototype for atoi:

int atoi(char *string_to_convert)

-Skatanic
 
heheheh I started typing the prototype in the code... change the line:
int number = atoi(char *str);
to:
int number = atoi(str);

Sorry...
 
Be careful with the value of the string though.

atoi() stands for alpha-to-integer

An integer too large will fail atoi. There are others that return long ints and unsigned long ints. Check them out as they may be useful.

Here I've listed some conversion routines from a man page on UNIX (make sure they are available to you first).

strtol, strtoll, strtoul, strtoull, atol, atoll, atoi,
lltostr, ulltostr

Check the documentation as the "str" versions differ from the "a" versions on error..ie. sending the function a value too large to convert.

-tyler
 
Yeah...I actually managed to find the strtox functions while reading a man page for the atoi. And again it worked out really nicely...I'm able to read in decimal, hex, or octal values, which is really nice, and convert them straight to integer. Now if I could just get them into binary...:)

Thanks!
sean
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top