目前正在为我的CompSci课程开展彩票项目。
我有40个彩票球图像(1.BMP到40.BMP),我想使用for循环显示每个球。
如果我将displayBMP全部调用40次,我可以很好地显示它们,但必须有一个更漂亮的方法。
string type = ".BMP";
for(int i = 0; i < 40; i++)
{
char alphanum = i;
//char* name = combine alphanum and type
displayBMP(name, randomX(), randomY());
}
修改
尝试将此垃圾放入.cpp文件中作为我的标题。
#include "Lottery.h"
void Lottery::initDisplay()
{
//Draw Some Lines
//Display Lottery balls 1-40
}
有什么想法吗?
答案 0 :(得分:0)
我想你想要:
1.BMP
2.BMP
3.BMP
4.BMP
等。
该代码为:
非C ++ 11:
#include <sstream>
template <typename T>
std::string ToString(T Number)
{
std::stringstream ss;
ss << Number;
return ss.str();
}
std::string type = ".BMP";
for(int i = 0; i < 40; i++)
{
displayBMP(ToString(i) + type, randomX(), randomY());
}
使用C ++ 11:
std::string type = ".BMP";
for(int i = 0; i < 40; i++)
{
displayBMP(std::to_string(i) + type, randomX(), randomY());
}
答案 1 :(得分:0)
您可以在字符串类中使用函数c_str()来返回const char *
因此,如果第一种类型的displayBMP是const char *
e.g。
std::string type = ".BMP";
for(int i = 0; i < 40; i++)
{
char alphanum = i;
std::string name = "" + alphanum + type;
displayBMP(name.c_str(), randomX(), randomY());
}
但是,类型是char *
e.g。
std::string type = ".BMP";
for(int i = 0; i < 40; i++)
{
char alphanum = i;
std::string name = "" + alphanum + type;
displayBMP(&name[0], randomX(), randomY());
}
在这里,我建议将名称的类型转换为更方便的字符串, 如果您不想更改displayBMP中的名称,第一个示例将更多 直觉