String–cannot convert from ‘const char *’ to ‘LPTSTR’错误

这种错误,很多情况下是类型不匹配

LPTSTR表示为指向常量TCHAR字符串的长指针

TCHAR可以是wchar_tchar,基于项目是多字节还是宽字节版本。

看下面的代码,代码来源:Example: Open a File for Reading

DisplayError(TEXT("CreateFile"));

void DisplayError(LPTSTR lpszFunction) 
// Routine Description:
// Retrieve and output the system error message for the last-error code
{ 
    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError(); 

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, 
        NULL );

    lpDisplayBuf = 
        (LPVOID)LocalAlloc( LMEM_ZEROINIT, 
                            ( lstrlen((LPCTSTR)lpMsgBuf)
                              + lstrlen((LPCTSTR)lpszFunction)
                              + 40) // account for format string
                            * sizeof(TCHAR) );

    if (FAILED( StringCchPrintf((LPTSTR)lpDisplayBuf, 
                     LocalSize(lpDisplayBuf) / sizeof(TCHAR),
                     TEXT("%s failed with error code %d as follows:\n%s"), 
                     lpszFunction, 
                     dw, 
                     lpMsgBuf)))
    {
        printf("FATAL ERROR: Unable to output error code.\n");
    }

    _tprintf(TEXT("ERROR: %s\n"), (LPCTSTR)lpDisplayBuf);

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
}

编译的时候,会出现标题中的错误,

错误处: 

DisplayError(TEXT("CreateFile"));

并且在调试时,我们会发现出现????这样的错误,检查参数时会发现一堆奇怪的文字。

原因是在宽字节版本下,我们传入的是单个字节,而wchar_t*指向它们的字符将期望每个字符都是2字节,所以就会出现????

我们可以这样简单的转换,宽字节版本: 

DisplayError((LPTSTR)L"CreateFile");

多字节版本:

DisplayError((LPTSTR)"CreateFile");

但是我们最好要停止使用TCHAR类型,取而代之,使用mbstowcs()或MultiByteToWideChar()将char字符串转换为utf16。或始终使用wchar_t std :: wstring

多字节版本:

std::string str = "CreateFile";
const char* lp = str.c_str(); // or
LPCSTR lp = str.c_str();

宽字节版本:

std::wstring wstr = L"CreateFile";
const wchar_t* lp = wstr.c_str() // or
LPCWSTR lp = wstr.c_str();

 另附mbstowcs的用法:

   std::string str = "CreateFile"; //多字节
   wchar_t wstr[11];
   mbstowcs(wstr, str.c_str(), str.size()+1);
   DisplayError(wstr); //宽字节版本

 

原文链接: https://www.cnblogs.com/strive-sun/p/14296780.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    String--cannot convert from 'const char *' to 'LPTSTR'错误

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/404726

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月25日 下午4:41
下一篇 2023年4月25日 下午4:42

相关推荐