我正在尝试将字符串转换为“LPCTSTR”,但是出现以下错误。
错误 :
cannot convert from 'const char *' to 'LPCTSTR'
代码:
std::string str = "helloworld";
LPCTSTR lp = str.c_str();
另外,尝试过:
LPCTSTR lp = (LPCTSTR)str.c_str();
但是,打印垃圾值。
我正在尝试将字符串转换为“LPCTSTR”,但是出现以下错误。
错误 :
cannot convert from 'const char *' to 'LPCTSTR'
代码:
std::string str = "helloworld";
LPCTSTR lp = str.c_str();
另外,尝试过:
LPCTSTR lp = (LPCTSTR)str.c_str();
但是,打印垃圾值。
LPCTSTR
表示(指向常量TCHAR
字符串的长指针)。
ATCHAR
可以是wchar_t
或char
基于您的项目设置。
如果在您的项目设置中,在“常规”选项卡中,您的字符集是“使用多字节字符集”,那么TCHAR
它是char
. 但是,如果它设置为“使用 Unicode 字符集”,那么TCHAR
它就是一个别名wchar_t
。
您必须使用 Unicode 字符集,因此:
LPCTSTR lp = str.c_str();
现实中是:
// c_str() returns const char*
const wchar_t* lp = str.c_str();
这就是您收到错误的原因:
无法从“const char *”转换为“LPCTSTR”
您的线路:
LPCTSTR lp = (LPCTSTR)str.c_str();
现实中是:
const wchar_t* lp = (const wchar_t*) std.c_str();
在 astd::string
中,字符是单字节,wchar_t*
指向它们会期望每个字符是 2+ 字节。这就是为什么你会得到无意义的价值观。
最好的办法是按照 Hans Passant 的建议——不要使用基于TCHAR
. 在您的情况下,请改为执行以下操作:
std::string str = "helloworld";
const char* lp = str.c_str(); // or
LPCSTR lp = str.c_str();
如果你想使用 Windows 调用 Unicode 的宽字符,那么你可以这样做:
std::wstring wstr = L"helloword";
const wchar_t* lp = wstr.c_str() // or
LPCWSTR lp = wstr.c_str();