Convert Integer to String

Started by
8 comments, last by Drew_Benton 19 years ago
Hi.. i need some SIMPLE code to convert integers to strings... i'm trying to do a loop that increments a number and add it to a string to form a filename.. like screenshot 00,screenshot 01..screenshot 10. and i also get a blank string when i use lstrcat.. i need a bit of help with that too....thanks
Advertisement
You should at something like sprintf in the MSDN, it should do what you want.
Its not a bug, its a feature!!
Use itoa.
Quote:Each of these functions returns a pointer to string.
- A momentary maniac with casual delusions.
I should be shot for this using sprintf, but ohh well...

// this number can be incremented every time you want to take another screenshotint currentScreenshotNumber = 1;char ScreenshotName[1024];sprintf(ScreenshotName, "ImageName%02d.tga", currentScreenshotNumber);


This give you file name like:
"ImageName01.tga" if currentScreenshotNumber = 1,
"ImageName02.tga" if currentScreenshotNumber = 2,
etc..




If you want a more c++ aproach (assuming you're using c++) you could try boost::lexical_cast, which takes advantage of the conversion code already in the stl.

It looks a little something like this
#include <boost/lexical_cast.hpp>//...int Foo = 42;std::string StringFoo = boost::lexical_cast<std::string>( Foo );
Use sprintf(), itoa() is not guaranteed to be implemented on all the platforms (for example, FreeBSD doesn't have it).
I have no problem with sprintf. In fact, it's what I use. Just keep your brain in order when you use it and you should be fine.
Quote:
Lots of recommendations for sprintf by several posters


Advice from Exceptional C++ style (and unfortunately not, therefore, in GotW):

If you're just converting a value to string : use boost::lexical_cast
For simple formatting (and some other, probably-not-relevant-to-you conditions) : use stringstream or strstream
For complex formatting : use snprintf
If performance matters : use strstream or snprintf
Never use sprintf

The basic raison d'etre for one topic in the afore-mentioned book is that snprintf offers everything sprintf does, but also helps eliminate buffer overruns. Ergo - never use sprintf, use snprintf (if another option (*cough* boost) doesn't meet your needs).

Jim.
if hes casting an int to a string then adding to another string, wouldnt it be easier if he just used a string stream (no boost either)
#include <sstream>ostringstream os;os << 10 << 11 << 12 << 13;os << 14;string a = os.str();
Quote:Original post by Genjix
if hes casting an int to a string then adding to another string, wouldnt it be easier if he just used a string stream (no boost either)
*** Source Snippet Removed ***


Yeap. I don't know why I have not seen any Standard C++ Library examples, it must have been because of this thread...[wink]

This topic is closed to new replies.

Advertisement