如何在 const wchar_t* 参数处进行连接?

How to make concatenations at const wchar_t* parameters?

在这种情况下,如何在 const wchar_t* 参数处进行串联?

我正在尝试使用以下名称自动保存屏幕截图:

screen-1.jpg
screen-2.jpg
screen-3.jpg
...
screen-i.jpg`

代码:

p_bmp->Save(L"C:/Users/PCUSER/AppData/screen-" + filenumber + ".jpg", &pngClsid, NULL);
 //filenumber is ant int that increases automatically

但是它给我一个错误:

expression must have integral or unscoped

原始 C 风格字符串指针(如 const wchar_t*)无法使用 operator+ 与字符串语义连接在一起。但是,您可以连接 C++ 字符串 classes 的实例,例如 ATL CStringstd::wstring,仅举几例。

因为您还有 整数 值要连接,您可以先将它们转换为字符串对象(例如使用 std::to_wstring()),然后使用重载的 operator+ 连接各种字符串。

#include <string> // for std::wstring and to_wstring()
...

// Build the file name string using the std::wstring class
std::wstring filename = L"C:/Users/PCUSER/AppData/screen-";
filename += std::to_wstring(filenumber); // from integer to wstring
filename += L".jpg";

p_bmp->Save(filename.c_str(), // convert from wstring to const wchar_t*
            &pngClsid, 
            NULL);

如果您使用 ATL CString class,您可以采用的另一种方法是以类似于 printf() 的方式格式化结果字符串,调用 CString::Format() 方法,例如:

CStringW filename;
filename.Format(L"C:/Users/PCUSER/AppData/screen-%d.jpg", filenumber);

p_bmp->Save(filename, // implicit conversion from CStringW to const wchar_t*
            &pngClsid, 
            NULL);