Int To String (char*)

Started by
13 comments, last by Anonymous0 22 years, 2 months ago
actually "atof" operates on "double". so you''ll have to explicitly type cast.

also there is "strtol", "strtoul", and "strtod".

and under MSVC++ there is "_i64toa" for 64-bit integers. tho, this is NOT ANSI.

To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.
To the vast majority of mankind, nothing is more agreeable than to escape the need for mental exertion... To most people, nothing is more troublesome than the effort of thinking.
Advertisement
C++: std::stringstream. Type-safe, flexible, generic, transparent, easy to use...

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!
    ??=include<stdio.h>??=define m mainint m(int c,char**g)??<static char n??(??)="0123456789abcdefghijklmnopqrstuvwxyz                                ";int o=sizeof(n)/sizeof(*n)-1;switch(c++)??<case 1:for(;(printf("Please enter a number (0 to exit): "),scanf("%d",(int*)g),*(int*)g);1??(g??)=(char*)16,printf("That number in hex: %s\n",(char*)m(c,g)),1??(g??)=(char*)2,printf("That number in binary: %s\n",(char*)m(c,g)));break;default:int v=(int)0??(g??),b=(int)1??(g??);if(!((0==b)??!??!(b>36)))do(--o)??(n??)=(v%b)??(n??);while((v/=b));??>return(int)(n+o);??>    

Edit: Some additional functionality was added. The routine will convert to any base from 2 to 36, but doesn't handle negative numbers properly; that requires inelegant special-casing.

Edited by - DrPizza on January 29, 2002 3:37:58 PM
char a[99999],*p=a;int main(int c,char**V){char*v=c>0?1[V]:(char*)V;if(c>=0)for(;*v&&93!=*v;){62==*v&&++p||60==*v&&--p||43==*v&&++*p||45==*v&&--*p||44==*v&&(*p=getchar())||46==*v&&putchar(*p)||91==*v&&(*p&&main(0,(char**)(--v+2))||(v=(char*)main(-1,(char**)++v)-1));++v;}else for(c=1;c;c+=(91==*v)-(93==*v),++v);return(int)v;}  /*** drpizza@battleaxe.net ***/
But seriously, folks, you probably want something like a conversion_cast function:
  template<typename O, typename I>O conversion_cast(const I& rhs){	std::stringstream ss;	ss << rhs;	O output;	ss >> output;	return output;}  

So you would say, for instance:
  std::string myString = conversion_cast<std::string>(myInt);  

If you *really* want a char*, you use std::string::c_str().
char a[99999],*p=a;int main(int c,char**V){char*v=c>0?1[V]:(char*)V;if(c>=0)for(;*v&&93!=*v;){62==*v&&++p||60==*v&&--p||43==*v&&++*p||45==*v&&--*p||44==*v&&(*p=getchar())||46==*v&&putchar(*p)||91==*v&&(*p&&main(0,(char**)(--v+2))||(v=(char*)main(-1,(char**)++v)-1));++v;}else for(c=1;c;c+=(91==*v)-(93==*v),++v);return(int)v;}  /*** drpizza@battleaxe.net ***/
Exactly what lexical_cast does over on boost.


- Houdini

Edited by - Houdini on January 29, 2002 3:35:54 PM
- Houdini

This topic is closed to new replies.

Advertisement