CString ,string, char 的操作

来源:互联网 发布:用友软件的售后 编辑:程序博客网 时间:2024/05/17 08:12

Cstring 转到string : --->string sTemp String = strAccountName.GetBuffer(0);

string 转到char:----->memcpy(sendpacket.szLoginUserID, Act_Table.front().name.c_str(),20);

用c_str()

 

///////////////////////////

1

char * 转WCHAR *:

::MultiByteToWideChar(CP_ACP,0,(const char *)res,int count,char * dest,int count);

类似地,WCHAR *转char *:

WideCharToMultiByte(CP_ACP,   0,.........);

CString 转WCHAR *:

wchar_t * p=str.AllocSysStrinig()

也有A2W(str)的,但是要包括ATL转换头文件#include;

并且在A2W前使用USES_CONVERSION宏。

其它:

char*转CString:

除了直接赋值外,还可使用CString::Format进行。

如char * p="sfdasf";

CString str=p; 或者str.Format("%s",p);


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

2

VS2008项目属性有Mutil-Byte和Unicode两种,Cstring中的字符采用TCHAT编码,而TCHAR在Unicode下是char 8位表示已个字符。在Mutil中是WCHAR即16位表示一个字节。

所有在Mutil-Byte中 char *p=(LPCTSTR)CString就正确。

在Unicode错误。因为Unicode编码项目中,此时为WCHAR了。即使强制转换也会出先数据丢失问题。

所以要用一下方法

头文件 #include "atlbase.h"

 

代码中:

 USES_CONVERSION; 

 LPCSTR *p=W2A(CString);

 

这样就有另外一个问题,如何实现LPCSTR 到CSTRING的转化呢?

  LPWSTR wst=A2W(P);

在Unicode下, CString就是LPWSTR类型。所以直接用就可以了。

 CString test=wst;


////////////////////////////这下面是我自己的原创,也借鉴了别人的////////////////////////////////////////////////////////

特此声明,CStringToChar在vc2010下测试通过没有问题,但是在2008下有问题,无法用的,CStringToString在2008下没有测,暂时无法知道结果

3

重点:谈下面这个

CString 转char *

char* CStringToChar( CString& strRourc )
{
char* sz = 0;
 int nlen = 0;
 nlen = WideCharToMultiByte(CP_ACP,0,strRourc.GetBuffer(),-1,NULL,0,NULL,NULL);
 sz = new char[nlen+1];
 memset( ( void* )sz, 0, sizeof( char ) * ( nlen + 1 ) );
 if (sz)
 {
  nlen = WideCharToMultiByte(CP_ACP,0,strRourc.GetBuffer(),-1,(LPSTR)sz,MAX_PATH,NULL,NULL); 
  return sz;
 }
 return sz;
}

调用完了,外面切记一定要delete,



2008下,这么做可以转换:


CString temp, str=_T("12345");
LPTSTR t = str.GetBuffer(255);
temp.Format("%ld", _tcstol(str.GetBuffer(255), NULL, 10) );


////////////接上面,再给个string版本的

void CStringToString( CString& strRourc ,string& str)
{
 char*  pElementText = NULL;
 int    nTextLen = 0;
 // wide char to multi char
 nTextLen = WideCharToMultiByte( CP_ACP,
  0,
  strRourc.GetBuffer(),
  -1,
  NULL,
  0,
  NULL,
  NULL );
 pElementText = new char[nTextLen + 1];
 memset( ( void* )pElementText, 0, sizeof( char ) * ( nTextLen + 1 ) );
 ::WideCharToMultiByte( CP_ACP,
  0,
  strRourc.GetBuffer(),
  -1,
  pElementText,
  nTextLen,
  NULL,
  NULL );
 
 str = pElementText;
 delete[] pElementText; 

pElementText = NULL;

}

 以上只是我自己的记录。

哪位有需要借鉴的,各取所需吧


另外 参考:http://blog.csdn.net/diablof/article/details/8276966

原创粉丝点击