cannot convert from 'const char *' to 'LPCTSTR'

半世苍凉 提交于 2019-12-01 14:52:48
Zebrafish

LPCTSTR means (long pointer to constant TCHAR string).

A TCHAR can either be wchar_t or char based on what your project settings are.

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.

You must be using the Unicode character set, so:

LPCTSTR lp = str.c_str();

Is in reality:

// c_str() returns const char*
const wchar_t* lp = str.c_str();

This is why you're getting the error:

cannot convert from 'const char *' to 'LPCTSTR'

Your line:

LPCTSTR lp = (LPCTSTR)str.c_str();

Is in reality:

const wchar_t* lp = (const wchar_t*) std.c_str(); 

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.

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();

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!