Sign in to follow this  
Monkey_Missile

Help with for loops and strings when loading files.

Recommended Posts

With C++ and SDL I'm having a bit of a brain fart remembering and finding the syntax for what I'm trying to do. I have a for loop in a function that is loading files into an array. (char* file, int number) are the two parameters of the function where file is the first part of the file name and number is the number of files. I have the files named as such:

example0.png
example1.png
example2.png

The code for the for loop is as follows:

[code]for (int i = 0; i < number; i++)
{
Array[i] = OnLoad((file) + i + ".png") ;
}[/code]

OnLoad is a function I have for loading files which works independently of this. My question is when I pass the parameters "example" and "3" to the function and thus this for loop how do I have the above translate it into "example0.png" and so on.

Share this post


Link to post
Share on other sites
You're using C++, so you should be using std::string, but anyways...
[code]
std::ostringstream ss;
ss<<file<<i<<".png";
std::string filename = ss.str();
[/code]
ostringstream is located in the <sstream> header.

Share this post


Link to post
Share on other sites
[quote name='Washu' timestamp='1329790092' post='4915031']
You're using C++, so you should be using std::string, but anyways...
[code]
std::ostringstream ss;
ss<<file<<i<<".png";
std::string filename = ss.str();
[/code]
ostringstream is located in the <sstream> header.
[/quote]
Is there any reason to do this vs:
[code] OnLoad(string(file) + '0'+i+ ".png") [/code]

Share this post


Link to post
Share on other sites
And the instant i is no longer a number between 0 and 9 you would immediately fail. Btw, the character immediately after '9' is ':', which as you can imagine doesn't work out so well in the middle of a filename.

Share this post


Link to post
Share on other sites
[quote name='rip-off' timestamp='1329817460' post='4915130'] You could always lexical_cast<> it, which would hide the details of the conversion (as we don't really care about them in this case). [/quote]

True, if he's using boost. If he's using a modern compiler AND C++0x he might have access to std::to_string functionality as well.

However, this is For Beginners, so the best answer is usually the one that requires the fewest number of "If you have X and version of X is greater than Y" or "if you have X installed and configured correctly", which in this case happens to be stringstream.

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