Fixing some stuff...

Published November 28, 2005
Advertisement
I've been looking over the code for Stompy 2, and I noticed one thing I really wanted to change.

In any tile based game I do, I like to rename the filenames of the tile graphics 0, 1, 2 and so forth, so that I can load them all into an array with one for-loop:
// Load in tilesetfor(int i = 0; i < NUM_TILES; i++){    char filename[20];    sprintf(filename, "gfx/Tiles/%d.bmp", i);    tiles = SDL_LoadBMP(filename);    if(!tiles)        // error}


Although this works, I want to use std::string whenever I need to do any string related processing. Plus, I've heard using sprintf() is a definite no-no. So this would be the new version:
// Load in tilesetfor(int i = 0; i < NUM_TILES; i++){    std::ostringstream filename;    filename << "gfx/Tiles/" << i << ".bmp";    tiles = SDL_LoadBMP(filename.str().c_str());        if(!tiles)       // error}


Does the same thing, but it is now very C++-ified and it fits in well with the rest of my STL heavy code.
Previous Entry More scripting stuff...
Next Entry Yay! Demo!
0 likes 3 comments

Comments

nilkn
If you're curious, a similar method of concatenating numbers onto strings is to use boost::lexical_cast.

It can be used thusly:

std::string = "gfx/Tiles/" + boost::lexical_cast< std::string >( i ) + ".bmp";
November 28, 2005 08:10 PM
Stompy9999
That also looks like a good solution. I haven't used any boost yet in my code, but it sounds like something I should try.
November 28, 2005 09:55 PM
mikedoty
I've never had any trouble with sprintf. Maybe if you're doing some intensive string manipulation it is disadvantageous, I don't know. You could also use atoi() to convert integers to characters, though if you're using std::string chars might not help you much.
November 28, 2005 10:39 PM
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Advertisement
Advertisement