如何在作为参数传递时附加到字符串而不更改原始值
How to append to a string without changing original value when passing as a parameter?
我正在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());
相关文章:
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 如何在连接器 C++ 中将原始字节转换为字符串
- 将以 null 结尾的字节字符串转换为原始字符串文本
- 是否可以在原始字符串文本中插入转义序列?
- 如何找到修改后的字符串与原始字符串相等的时间
- 如何在c++中打印原始std::string/c样式的字符串
- 是否存在像C++中那样带有分隔符的C#原始字符串
- 反转由空格分隔的字符串元素将返回比原始字符串更大的字符串
- C++ 原始字符串 Unicode 文字
- 编码大于原始文本:如何获取零和一的字符串并将它们作为实际字节写入文件
- 在对原始字符串进行一些处理后返回(或转换)原始字符串
- 打印可以重复以获取原始字符串的最小字符串
- 如何从字符串变量为正则表达式构建原始字符串
- 如何制作包含原始字符串终止符C++原始字符串
- 如何在 C++ VS 中使用原始字符串文字(编码问题)
- 如何将变量用作原始 JSON 字符串中的数据?
- 什么是原始字符串?
- 转义 R "()" 在 C++ 中的原始字符串中
- 原始字符串比普通字符串快
- C++多行字符串原始文字