Wednesday, June 11, 2008

Convert wchar_t* to char* - VC++

Convert Unicode character to No set

Method1:

//if succeed returns newly allocated char pointer.else NULL.
//Note-> the return pointer should be deleted
char* WideCharToChar(LPCWSTR lpWideCharStr)
{
      size_t length = wcslen(lpWideCharStr);
      ++length;
     
char* lpszConvertedStr = new char[length];
     
int nReturnVal =  WideCharToMultiByte( CP_OEMCP, 0, lpWideCharStr, -1,lpszConvertedStr, (int)length, NULL, NULL );
     
//If not succeed delete pointer
      if( 0 == nReturnVal)
      {
           
delete[] lpszConvertedStr;
            lpszConvertedStr = NULL;
      }
     
return lpszConvertedStr;
}

Method2: Using CStringT

Everybody know that CString is the typedef of ATL::CStringT
So we can convert Unicode character to No set with the help of these template class.
Example:
      CStringW strUnicode = L"Unicode String";
      CStringA strNoUnicode =
"Non Unicode string";
      strUnicode = strNoUnicode;
// here  non unicode to Unicode.
      strNoUnicode = strUnicode;// Unicode to non unicode

 

 

No comments: