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); //宽字节版本
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值