如何连接字符串和整数以生成文件名
How do I concatenate a string and an integer to make a filename?
我有一系列文件(New1.BMP, New2.BMP,…,New10.BMP)。
我需要创建一个变量来存储上述文件的名称,然后在另一段代码中使用它。
我的当前代码:
int LengthFiles =10;
char FilePrefix[100]="New";//This is actually passed to the function. Am changing it here for simplicity
char str[200],StrNumber[1];//str holds the file name in the end. StrNumber is used to convert number value to character
SDL_Surface *DDBImage[9]; // This is a SDL (Simple DIrectMedia Library) declaration.
for (int l=0;l<LengthFiles ;l++)
{
itoa(l, StrNumber, 1);
strcat(str,FilePrefix);strcat(str,StrNumber);strcat(str,".BMP");
DDBImage[l]= SDL_DisplayFormat(SDL_LoadBMP(str));
}
正如您可能看到的,我不知道如何在c++中编写代码,我试图从在线代码片段中完成此工作。在C/c++中应该是这样工作的吗?即动态地创建变量。
我如何最好地接近它?
你原来的问题标题有点误导人,因为你实际上想做的是将字符串和整数连接起来。
在c++中,你可能会用stringstream
:
stringstream ss;
ss << "New" << l << ".bmp";
然后得到string
变量:
string filename = ss.str();
最后使用c_str()
:
SDL_LoadBMP(filename.c_str())
DDBImage
申报错误。您需要一个长度为10的数组,但您声明它的长度为9。如果您将LengthFiles
写入常量,则可以写入SDL_Surface *DDBImage[LengthFiles]
,从而确保数组的长度正确。
代码可能看起来像这样:
const int FileCount = 10;
SDL_Surface *DDBImage[FileCount];
for (int index=0; index<FileCount; index++)
{
stringstream ss;
ss << "New" << index << ".bmp";
string filename = ss.str();
DDBImage[index] = SDL_DisplayFormat(SDL_LoadBMP(filename.c_str()));
}
如果你的文件名真的以New1.bmp
开头,那么你需要调整索引:
ss << "New" << index+1 << ".bmp";
最后,如果您需要扩展它来处理在运行时确定的可变数量的文件,那么您应该使用vector<*DDBImage>
而不是原始数组。使用vector<>
允许您让c++标准库为您处理低级内存管理。事实上,任何时候你发现自己在用c++编程时分配内存,你应该问自己是否已经有一些标准库可以为你做这件事。
您可以使用格式化字符串printf…大致沿着
sprintf( str, "%s%d.BMP", prefix, fileNumber );
看看http://www.cplusplus.com/reference/cstdio/sprintf/
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 从命令行c++发送文本文件名
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 序列化,没有库的整数,得到奇怪的结果
- 在一定长度后从数组中打印时缺少整数
- 如何连接字符串和整数以生成文件名