VC2008中将CString转换成const char*的一种有效方法

来源:互联网 发布:视频片头片尾制作软件 编辑:程序博客网 时间:2024/06/07 02:45

     文章转载自http://blog.csdn.net/lanbing510/article/details/7425613

     在Visual Studio 200X下,CString直接转换成const char* 有点困难,下面是自己用的一种可行方案:

     从网上找了一些CString变量转换成const char*的方法,一种有效的办法是使用WideCharToMultiByte库函数进行转换。

     将LPCTSTR转换为const char *,因为Unicode的问题,LPCTSTR
     1、在非UNICODE环境下为 const char *
     2、在UNICODE环境下为 const unsigned short *

     VS2008默认的字符集是Unicode,而VC6.0默认是多字节字符集,Unicode字符集你要加_T("")或L"",你也可以“工程-属性-修改字符集”。

     在情况2时需要借助API函数WideCharToMultiByte进行转换。其函数原型如下所示:

    int WideCharToMultiByte( 
      UINT CodePage,            // code page 
      DWORD dwFlags,            // performance and mapping flags 
      LPCWSTR lpWideCharStr,    // wide-character string 
      int cchWideChar,          // number of chars in string 
      LPSTR lpMultiByteStr,     // buffer for new string 
      int cbMultiByte,          // size of buffer 
      LPCSTR lpDefaultChar,     // default for unmappable chars 
      LPBOOL lpUsedDefaultChar  // set when default char used 
    ); 

    可以写一个将CString变量转换成char*类型转换函数如下:

//将CString变量转换成char*类型char* CStringToCharArray(CString cStr){char *ptr;#ifdef _UNICODELONG len;len = WideCharToMultiByte(CP_ACP, 0, cStr, -1, NULL, 0, NULL, NULL);ptr = new char [len+1];memset(ptr,0,len + 1);WideCharToMultiByte(CP_ACP, 0, cStr, -1, ptr, len + 1, NULL, NULL);#elseptr = new char [cStr.GetAllocLength()+1];sprintf(ptr,_T("%s"),cStr);#endifreturn ptr;}


 

	
				
		
原创粉丝点击