'Creating a partial file name with a variable in C++

I'm making a C++ program/game that uses the "graphics.h" header and I'm trying to create a map with tiles. There are 66 tiles and each file name is different. I want to display them all without having to write nearly identical lines over and over.

This is what I have so far (pseudocode):

filename = a + number + b;
readimagefile (filename, left, top, right, bottom);

Where a is "bg(", followed by a number from 1 to 66, and then b, which is ").bmp". I want the filename to be like this: "bg(number).bmp". However, what I have above is clearly the incorrect syntax.

How would I go about doing this? Thanks in advance for any answers.



Solution 1:[1]

std::stringstream str;
str << a << number  <<  b << ".bmp";

Then str.str() returns a c++ std::string and str.str().c_str() returns a 'c' type string

Solution 2:[2]

In C++11, a number may be converted to its string representation using to_string (or to_wstring). For example,

a + std::to_string(number) + b

(The Visual C++ 2012 Standard Library implementation includes to_string and to_wstring.)

This is far more straightforward (less code, easier to read) than creating a std::stringstream to do the formatting (it's also less capable and more restricted, but for simple use cases like the one you describe, it is sufficient).

Alternatively, Boost.LexicalCast may be used to convert an object to a string; internally it uses a std::stringstream, but it may be optimized for numeric types and other types for which using a stream would be overkill. Using boost::lexical_cast:

a + boost::lexical_cast<std::string>(number) + b

Solution 3:[3]

for(int i=0; i<66; i++)
{
   stringstream stream;
   stream << "bg(" << i << ").bmp";
   string fileName = stream.str();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin Beckett
Solution 2 James McNellis
Solution 3 sithereal