Sign in to follow this  
ww3031

Convert Integer to String

Recommended Posts

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

Share this post


Link to post
Share on other sites
I should be shot for this using sprintf, but ohh well...


// this number can be incremented every time you want to take another screenshot
int 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..




Share this post


Link to post
Share on other sites
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 );

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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();

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this