如何连接字符串和整数以生成文件名

How do I concatenate a string and an integer to make a filename?

本文关键字:整数 文件名 字符串 何连接 连接      更新时间:2023-10-16

我有一系列文件(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():

将C字符串传递给SDL函数
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/