简体   繁体   中英

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.

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

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
for(int i=0; i<66; i++)
{
   stringstream stream;
   stream << "bg(" << i << ").bmp";
   string fileName = stream.str();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM