Saturday, February 19, 2011

lptstr to char*

Would anyone hapen to know how to convert a LPTSTR to a char* in c++?

Thanks in advance, workinprogress.

From stackoverflow
  • Here are a lot of ways to do this. MFC or ATL's CString, ATL macros, or Win32 API.

    LPTSTR szString = _T("Testing");
    char* pBuffer;
    

    You can use ATL macros to convert:

    USES_CONVERSION;
    pBuffer = T2A(szString);
    

    CString:

    CStringA cstrText(szString);
    

    or the Win32 API WideCharToMultiByte if UNICODE is defined.

  • Depends if it is Unicode or not it appears. LPTSTR is char* if not Unicode, or w_char* if so.

    Discussed better here (accepted answer worth reading)

  • char * pCopy = NULL;
    if (sizeof(TCHAR) == sizeof(char))
    {
        size_t size = strlen(pOriginal);
        pCopy = new char[size + 1];
        strcpy(pCopy, pOriginal);
    }
    else
    {
        size_t size = wcstombs(NULL, pOriginal, 0);
        pCopy = new char[size + 1];
        wcstombs(pCopy, pOriginal, size + 1);
    }
    
  • Thanks for the help!

0 comments:

Post a Comment