Tuesday, March 25, 2014

How to Convert CString to TCHAR*

There are two methods for converting a CString variable to TCHAR* variable

Basically CString belongs to ATL/MFC shared class / DLL you can convert CString into either string or a TCHAR variable of <tchar.h>

The exmaple below shows two implementations

#include<iostream>
#include<atlmfc.h>
#include<tchar.h>

int main( )
{

  CString strMyCS1("This is Method 1");

 TCHAR* pszmyTCHAR1=new TCHAR[strMyCS1.GetLength( )+1];

_tcscpy(pszmyTCHAR1,strMyCS1);

_tprintf("\n %s",pszmyTCHAR1);

delete[ ] pszmyTCHAR; //It is importatnt to use delete if you use new keyword

CString strMyCS2(_T("This is Method 2"));

TCHAR* pszmyTCHAR2=strMyCS2.GetBuffer( );

_tprintf("\n %s",pszmyTCHAR2);

strMyCS2.ReleaseBuffer( );

system("pause");

return 0;

}

output:

This is Method 1
This is Method 2
press any key....






No comments:

Post a Comment