zoukankan      html  css  js  c++  java
  • 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:
    %s"), 
                         lpszFunction, 
                         dw, 
                         lpMsgBuf)))
        {
            printf("FATAL ERROR: Unable to output error code.
    ");
        }
        
        _tprintf(TEXT("ERROR: %s
    "), (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); //宽字节版本
  • 相关阅读:
    杭电1075
    杭电1016深度搜索问题
    杭电1015
    stringstream
    向量的点乘和叉乘
    杭电1010
    FCKEditor2.6.3 配置
    JQuery实现全选 与 批量删除
    JQuery实现下拉框的选择 与当CheckBox为服务器控件时如何获取值的操作,实现全选与删除
    JS 对GridView的一些操作
  • 原文地址:https://www.cnblogs.com/strive-sun/p/14296780.html
Copyright © 2011-2022 走看看