cannot convert from 'const char *' to '

2019-02-21 06:50发布

问题:

I'm trying to convert string to 'LPCTSTR', but, i got following error.

Error :

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

code:

std::string str = "helloworld";
LPCTSTR lp = str.c_str();

Also, tried :

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

But, print garbage value.

回答1:

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