如何在作为参数传递时附加到字符串而不更改原始值

How to append to a string without changing original value when passing as a parameter?

本文关键字:字符串 原始 参数传递      更新时间:2023-10-16

我正在C++/SDL中制作PONG克隆,我的所有图像都在程序启动的目录中。我能够使用 GetCurrentDirectory(( 成功找到该路径并使用 strcat(( 打开文件以附加实际图像,它会加载正常,但这会更改原始值,这使得当我尝试加载下一个图像时它毫无用处。如何在不更改原始值的情况下传递路径,或者解决此问题的另一种方法。

我当前的代码:

    TCHAR openingdirectorytemp [MAX_PATH];
    bgtexturesurf = SDL_LoadBMP(strcat(openingdirectorytemp, "\bg.bmp"));

使用实际的C++字符串:

#include <string>
using std::string;
void child(const string str)
{
  str += ".suffix"; // parameter str is a copy of argument
}
void parent()
{
   string parents_string = "abc";
   child(parents_string);
   // parents_string is not modified
}

如果必须在 Windows API 世界中使用TCHAR,请使用std::basic_string<TCHAR>

typedef std::basic_string<TCHAR> str_t; // now use str_t everywhere

所以代码变成类似

void my_class::load_bg_bmp(const str_t &dir_path)
{
  str_t file_path = dir_path + _T("\bg.bmp")l
  bgtexturesurf = SDL_LoadBMP(file_path.c_str()));
  // ...
}

TCHAR 类型允许在窄字符和宽字符之间切换构建时间。使用TCHAR是没有意义的,但随后使用未包装的窄字符串文字,如"\bg.tmp"

另请注意,对未初始化数组的strcat会调用未定义的行为。要strcat的第一个参数必须是字符串:指向以 null 结尾的字符数组的第一个元素的指针。未初始化的数组不是字符串。

我们可以通过使用 C++ 字符串类来避免这种低级的讨厌。

尽管您可以按照其他答案的建议使用C++字符串,但您仍然可以保留 C 方法。

你需要做的只是通过复制原始内容来创建另一个字符串,并将其用于strcat:

TCHAR openingdirectorytemp [MAX_PATH];
TCHAR path [MAX_PATH];
strcpy(path, openingdirectorytemp);
bgtexturesurf = SDL_LoadBMP(strcat(path, "\bg.bmp"));

通过这样做,您可以创建具有单独内存空间的字符串path,因此 strcat 不会影响openingdirectorytemp

如果您担心事情会发生变化,则需要在连接之前复制字符串。换句话说,

string1 = "abc"
string2 = "def"
strcat(string1, string2);

结果在

string1 = "abcdef"

因为这是您要求程序执行的操作。相反,添加

strcpy(string3, string1)
strcat(string3, string2);

现在您将拥有

string1 = "abc" 
string3 = "abcdef"

当然,您需要确保分配足够的空间等。

使用 c++ 后,可以使用字符串来撰写最终路径名:

string pathname(path);
pathname += "\bg.bmp";
bgtexturesurf = SDL_LoadBMP(pathname.c_str());