# convert int to string

## Recommended Posts

biscuitz    127
How do I convert an int into a string?

##### Share on other sites
SiCrane    11839
In what language?

biscuitz    127
C/C++, win32

##### Share on other sites
SiCrane    11839
You can either use boost::lexical_cast or a std::stringstream.
std::stringstream sstr;sstr << my_int;std::string str1 = sstr.str();std::string str2 = boost::lexical_cast<std::string>(my_int);

biscuitz    127
:) Thanks

##### Share on other sites
std::string str = itoa(2342348);

Alternatively you can use atoi to convert back. I believe there are other C methods like atof and ftoa (f = float, i = int, a = *char .. XtoY())

##### Share on other sites
SiCrane    11839
itoa() isn't a standard C or C++ function, so there's no guarantee that a given C++ compiler will have it. Even if a C++ compiler has it, then there's no guarantee that the function will have the same function signature as the version you posted (most won't). On the compilers that do have a function signature that matches the version you just used, the code you posted may leak memory, as the return value will need to be free()'d.

itoa: just say no.

##### Share on other sites
Well, some do. If they do then take advantage of it I say.

Also, because the net here is so slow it took a while to come up with an example. (I don't use itoa that often, if ever)
char buffer [33];
std::string str = itoa (41515,buffer,10);

10 is the base, so if you wanted Hex you'd use 16 or binary would be base 2.

SiCrane: Yeah, I knew that would give a leak. That's why I searched for an example. This one shouldn't give a memeory leak.
Also boost isn't standard C\C++ either, so were on the same page. [grin]

##### Share on other sites
biscuitz    127
:S I tried using itoa with TextOut() and comes up with a bunch of characters on the end (which I don't want to show up) Ima try std strings.

##### Share on other sites
SiCrane    11839
Quote:
 Original post by PumpkinPiemanAlso boost isn't standard C\C++ either, so were on the same page. [grin]

There's only one boost::lexical_cast. There are at least eight different versions of itoa() out there. That's hardly the same page.

##### Share on other sites
biscuitz    127
I need help with stringstream method. I get error:
error: cannot convert std::string' to const CHAR*' for argument 4' to BOOL TextOutA(HDC__*, int, int, const CHAR*, int)'

o.O "cannot convert" I've tried using &, typecasting... I never ran into something that "couldn't be converted" to another type

##### Share on other sites
rip-off    10976
std::stringstream stream;stream<< my_int;std::string str = stream.str();// i dont use textout, so im not going to bother looking up the extra parameters// you probably have them right, the error specifically mentions parameter 4TextOut( one, two, three, str.c_str(), five );

##### Share on other sites
biscuitz    127
:/ Well that got rid of the error but doesn't do what I expected... Oh, how do I delete/clear the stringstream?

##### Share on other sites
Can't get any simpler than this:

int intValue = 4;
string strValue= "" + intValue;

[EDIT]
What would the disadvantage be if this appoarch was used instead of stringstream?

[Edited by - Deltasquadron2 on August 19, 2006 5:58:49 PM]

##### Share on other sites
Ronamitri    133
You can do something like this too:

char s[30];
int i=12345;

sprintf(&s[0], "%d", i);

##### Share on other sites
richardurich    1352
You may also use sprintf (stdio.h) to convert an integer to a char*. An example of the use would be sprintf(str,"%d",100). If you use sprintf, please use bounded versions to prevent buffer overflows.

There is no reason to use non-standard solutions for this problem, so generally stringstream or sprintf/sscanf would be preferrable. If your project is in C++ and uses string instead of char*, stick with stringstream.

##### Share on other sites
SiCrane    11839
Quote:
 Original post by biscuitz:/ Well that got rid of the error but doesn't do what I expected... Oh, how do I delete/clear the stringstream?

So what does it do? To clear a stringstream's contents you use str(""). To clear the status bits you use clear(). Depending on what you're doing with the stringstream you may need to use both.

##### Share on other sites
SiCrane    11839
Quote:

It just doesn't work. Try it.

##### Share on other sites
biscuitz    127
:D tnx again SiCrane, str("") did the trick. I tried that sprintf approach, was printing out stuff like "null...error....invalid"

[EDIT]
:( That added like 500kb of memory and disk space just to put a number on the screen.

[EDIT2]
Using the stringstream method. If the mouse position goes over 3 digits, then goes below, it keeps the numbers on the end. I'm trying to figure out how to fix it. Also amazed at how complicated it is just to put a friggen variable on the screen with standard functions.

[Edited by - biscuitz on August 19, 2006 6:41:11 PM]

##### Share on other sites
rip-off    10976
Quote:
 Original post by biscuitz:D tnx again SiCrane, str("") did the trick. I tried that sprintf approach, was printing out stuff like "null...error....invalid"[EDIT]:( That added like 500kb of memory and disk space just to put a number on the screen.[EDIT2]Using the stringstream method. If the mouse position goes over 3 digits, then goes below, it keeps the numbers on the end. I'm trying to figure out how to fix it. Also amazed at how complicated it is just to put a friggen variable on the screen with standard functions.

You need to clear the area under text thats already on the screen to black ( or whatever background colour ).

Imagine I write the string 100 to the screen.

If I then write 33 at the same start position, the number will look like 330.

If you clear the area underneath first this wont happen.

You cannot "put a variable to the screen with standard functions." The C++ standard makes no provision for graphics, so functions such as TextOut are provided in a library.

500kb is around .001 % of my system ram, not including virtual ram, which is nothing. Your hard drive is even bigger.

##### Share on other sites
biscuitz    127
lol i just figured out that I wasn't clearing that area (I figured it out cuz I changed the size of the window)

Actually I think you can put a variable onto the screen with standard functions. cin reads a variable and cout prints the variable =) Or you can use stringstream method but use cout to print out the text to screen without win32 api.

500kb is a big deal to me I mean 500 kb just to put the x and y position of the mouse on the screen is bloated, and I hate bloat-ware. I know 500kb isn't a lot but the fact is it went from under 100 kb to over 500 just by adding x/y position of mouse. 200kb would be nice.

I'll try to implement a sprintf method without showing all the padded characters >.>

##### Share on other sites
chowe6685    349
Are you compiling with any optimization whatsoever?

If you're in Visual Studio try the release build - the executable size will almost certainly be much smaller.

Please don't use sprintf over stringstreams just because it makes the executable size smaller. There's no reason to consider this bloatware and certainly no reason to give up the safety of c++ streams.

##### Share on other sites
biscuitz    127
hmm safety... Please point me to a site that explains the safety of stringstreams over sprintf (I'm new at this).

I know I have a strip optimization flag which'll cut the exe size *in half*. Well if the size increase is due to safety then that's not that bad.

##### Share on other sites
torakka    193
Why the binary must be small? Is there a reason?

Things that work for me:

- I am writing a winning 4K or 64K intro entry to competition like Assembly 2007
- I am writing for embedded device or similiar circumastances
- The binary must fit into limited storage media (floppy? <- why!? ;)
- Transfer time over network could be an issue (again, why!? :)

If the target is a desktop computer, reducing the size is not much interest. If switching from stringstream (?) to printf cuts the size of the binary into half, it looks like it is tiny to begin with which brings to another point: Code Is Small Anyway.

Yup: code is relatively tiny most of the time compared to the data associated with the code. Easiest way to blow up the size of the code is to generate inpractical use of permutations of code using templates, macros or similiar construct (speaking of C/C++ here different strokes with different languages). In this kind of situation the code isn't small anyway any longer.

Advice is being asked but the reason is not mentioned -- the reason and to be more precise, knowing it would be much more useful in evaluating the situation. So far I collected:

1. Number must be converted into readable form (I assume output for human to read, could also be written into a serialized form for storage, fileformat, whatnot!?)

2. This must be as small as possible: libraries implementing this are too large

I wonder WHY that is. The only reasonable answer to this set of limitations is: "write your own", "google for something that someone else wrote and use it", or, "rip the code from library implementation -- example: g++ comes with sourcecode, and you can also look inside runtime libs in other vendor's products with debugger and rip"

And so on.. but this is like bending backwards thrice for no benefit that I can see. Strange stuff. Please explain, my curiosity is at 11!!!

##### Share on other sites
torakka    193
Ooops.. forgot the point I had in mind when hit reply. :)

If the c++ library is too big, what makes the c version small enough? If the c version is small enough, why the c++ version then isn't small enough as it offers additional benefit of being typesafe!? I'm asking this because they aren't THAT much different size.. (compiler and standard library vendor withstanding..)