问题描述
我正在尝试将字符串转换为'LPCTSTR',但是,出现以下错误.
I'm trying to convert string to 'LPCTSTR', but, i got following error.
错误:
cannot convert from 'const char *' to 'LPCTSTR'
代码:
std::string str = "helloworld";
LPCTSTR lp = str.c_str();
也尝试过:
LPCTSTR lp = (LPCTSTR)str.c_str();
但是,打印垃圾值.
推荐答案
LPCTSTR
表示(指向常量TCHAR
字符串的长指针).
LPCTSTR
means (long pointer to constant TCHAR
string).
根据您的项目设置,TCHAR
可以为wchar_t
或char
.
A TCHAR
can either be wchar_t
or char
based on what your project settings are.
如果在项目设置的常规"选项卡中,字符集为使用多字节字符集",则TCHAR
是char
的别名.但是,如果将其设置为使用Unicode字符集",则TCHAR
是wchar_t
的别名.
If, in your project settings, in the "General" tab, your character set is "Use Multi-byte character set" then TCHAR
is an alias for char
. However, if it's set to "Use Unicode character set" then TCHAR
is an alias for wchar_t
instead.
您必须使用Unicode字符集,因此:
You must be using the Unicode character set, so:
LPCTSTR lp = str.c_str();
是现实中的
// c_str() returns const char*
const wchar_t* lp = str.c_str();
这就是为什么出现错误的原因:
This is why you're getting the error:
您的行:
LPCTSTR lp = (LPCTSTR)str.c_str();
是现实中的
const wchar_t* lp = (const wchar_t*) std.c_str();
在std::string
中,字符是单个字节,指向它们的wchar_t*
会期望每个字符都是2+字节.这就是为什么您会得到无意义的值.
In a std::string
, the chars are single bytes, having a wchar_t*
point to them will expect that each character is 2+ bytes instead. That's why you're getting nonsense values.
最好的做法是按照Hans Passant的建议-不要使用基于TCHAR
的typedef.在您的情况下,请执行以下操作:
The best thing to do would be as Hans Passant suggested - not to use typedefs based on TCHAR
. In your case, do this instead:
std::string str = "helloworld";
const char* lp = str.c_str(); // or
LPCSTR lp = str.c_str();
如果要使用Windows称为Unicode的宽字符,则可以执行以下操作:
If you want to use wide chars, which Windows calls Unicode, then you can do this:
std::wstring wstr = L"helloword";
const wchar_t* lp = wstr.c_str() // or
LPCWSTR lp = wstr.c_str();
这篇关于无法从"const char *"转换为"LPCTSTR"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!