0

我正在制作一个使用“graphics.h”标题的 C++ 程序/游戏,并且我正在尝试创建一个带有瓷砖的地图。有 66 个图块,每个文件名都不同。我想将它们全部显示出来,而不必一遍又一遍地编写几乎相同的行。

这是我到目前为止所拥有的(伪代码):

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

其中 a 是“bg(”,后跟 1 到 66 之间的数字,然后是 b,即“).bmp”。我希望文件名是这样的:“bg(number).bmp”。但是,我上面显然是不正确的语法。

我该怎么做呢?提前感谢您的任何答案。

4

3 回答 3

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

然后str.str()返回一个 c++ std::string 并str.str().c_str()返回一个 'c' 类型的字符串

于 2012-06-01T17:04:01.347 回答
2

to_string在 C++11 中,可以使用(或)将数字转换为其字符串表示形式to_wstring。例如,

a + std::to_string(number) + b

(Visual C++ 2012 标准库实现包括to_stringto_wstring。)

这比创建 astd::stringstream来进行格式化要简单得多(代码更少,更容易阅读)(它的功能也更小,也更受限制,但是对于像您描述的那样的简单用例,这就足够了)。

或者,可以使用Boost.LexicalCast将对象转换为字符串;在内部它使用 a std::stringstream,但它可以针对数字类型和其他类型进行优化,对于这些类型,使用流将是矫枉过正的。使用boost::lexical_cast

a + boost::lexical_cast<std::string>(number) + b
于 2012-06-01T17:07:20.450 回答
1
for(int i=0; i<66; i++)
{
   stringstream stream;
   stream << "bg(" << i << ").bmp";
   string fileName = stream.str();
}
于 2012-06-01T17:04:29.727 回答