Formating A String With Leading 0


PokeParadox

Founder of Pirate Games - Penjin Coder
Staff member
Joined
Dec 8, 2005
Messages
6,603
Age
40
Location
UK
Website
pokeparadox.itch.io
WEBSITE
https://github.com/pokeparadox
YOUTUBE
pokeparadox
OK well basically I'm looking for ways to tidy up my code and one thing that I've noticed the seems quite wasteful in terms of lines of code is that I have things like this:

CODE

// Setup sprites
dir = "images/";
ext = ".png";
string col = "red/";
redSprite.setUseHardware(true);
redSprite.loadFrame(dir+col+"01"+ext);
redSprite.loadFrame(dir+col+"02"+ext);
redSprite.loadFrame(dir+col+"03"+ext);
redSprite.loadFrame(dir+col+"04"+ext);
redSprite.loadFrame(dir+col+"05"+ext);
redSprite.loadFrame(dir+col+"06"+ext);
redSprite.loadFrame(dir+col+"07"+ext);
redSprite.loadFrame(dir+col+"08"+ext);
redSprite.loadFrame(dir+col+"09"+ext);
redSprite.loadFrame(dir+col+"10"+ext);
redSprite.loadFrame(dir+col+"11"+ext);
redSprite.loadFrame(dir+col+"12"+ext);
redSprite.loadFrame(dir+col+"13"+ext);
redSprite.loadFrame(dir+col+"14"+ext);
redSprite.setFrameRate(FIFTEEN_FRAMES);
redSprite.setLooping(true);



Now what I want to do is something like this:
CODE

StringUtility util;
// Setup sprites
dir = "images/";
ext = ".png";

string col = "red/";
redSprite.setUseHardware(true);
for(uint i=1; i < 15; i++)
{
redSprite.loadFrame(dir+col+util.intToString(i)+ext);
}
redSprite.setFrameRate(FIFTEEN_FRAMES);
redSprite.setLooping(true);



But that would load files: 1.png, 2.png, etc... but the filenames are 01.png, 02.png etc.

Obviously I could just rename the files but I kinda would like to avoid that! :)

EDIT: corrected error (< 14 now < 15) :p
 
C

char numstr[10];
sprintf(numstr, "%02d", i);

C++

ostringstream oss;
oss << setw(2) << setfill('0') << i;
string numstr = oss.str();
 
CODE
redSprite.loadFrame(dir+col+(i<10?"0":"")+util.intToString(i)+ext);


Parkydr: I had no idea formatted print had those neat tricks up its sleeve! I always used the logarithm function to achieve 0-padding in hiscore displays :D
 
Alex. said:
CODE
redSprite.loadFrame(dir+col+(i<10?"0":"")+util.intToString(i)+ext);
*mumbles off how you'd be better off with one large spritesheet and fewer 100byte png files* :rolleyes:


Agreed on that point! I just haven't wrote that into my class yet! ;)
But thanks guys! :)
 
Last edited by a moderator:
Seriously, sprintf is your best bet. It's standard, and I'm assuming it's faster than the logarithmic function on ARM. Not that you'd use that for one zero, but still...
 
Back
Top