StringCchCat 用于在 VC++ 中连接整数和字符串

StringCchCat for concatenating integers with strings in VC++

我想像这样连接整数和字符串:

我的代码片段是这样的。

TCHAR dest[MAX_PATH];
int i = 2;
StringCchCopy(dest,MAX_PATH,"Begining_");
StringCchCat(dest,MAX_PATH,LPCTSTR(i));

最后一行导致异常。我知道最后一行是错误的。 "Begining" & 连接后的字符串应为 "Begining_2"。我如何在 C++ 中实现这一点?

代码的快速修复:

TCHAR dest[MAX_PATH];
int i = 2;
_stprintf_s(dest, MAX_PATH, _T("Begining_%d"), i);

如您所见,我对其进行了简化并使其更加安全。所以不需要使用StringCchCopy/StringCchCat函数。

请注意,您使用的是纯 C 语言,在 Windows 平台上的 C++ 中,应该这样做:

使用 MFC 框架(符合 UNICODE):

int i = 2;
CString sDest;
sDest.Format(_T("Begining_%d"), i);

CString 确实有 (LPCTSTR) 转换运算符。所以你可以直接在任何接受 LPCTSTR 类型参数的函数中使用它。

标准 C++ 方式(符合 UNICODE):

int i = 2;
std::wstring dest(L"Begining_");
dest += std::to_wstring(i);
LPCWSTR str = dest.c_str();

试试这个代码

int i = 2;
std::wstring ext = std::to_wstring(i);  // convert integer to wstring
StringCchCat(dest, MAX_PATH, ext.c_str()); // pass wstring here