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

时间:2013-10-09 01:34:26

标签: c++ sdl

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

我目前的代码:

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

4 个答案:

答案 0 :(得分:1)

使用实际的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的第一个参数必须是一个字符串:指向空终止字符数组的第一个元素的指针。未初始化的数组不是字符串。

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

答案 1 :(得分:0)

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

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

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

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

答案 2 :(得分:0)

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

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

结果

string1 = "abcdef"

因为那是你要求程序做的。相反,添加

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

现在你有了

string1 = "abc" 
string3 = "abcdef"

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

答案 3 :(得分:0)

使用c ++后,可以使用string来组成最终路径名:

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

bgtexturesurf = SDL_LoadBMP(pathname.c_str());