您的位置:首页 > 其它

char,string,cstring之间的相互转换

2012-12-30 14:52 513 查看
#include <iostream>
#include <string>
#include <atlstr.h>		//非MFC工程下包含
#include <atlconv.h >

int main()
{
using namespace std;
USES_CONVERSION;				//转化字节需要
int age[3] = {0} ;					//数组初始化

/***************************************************/
/*  char 转化为 string                             */
/***************************************************/
char cCharToStr1[20] = "chartostr1";
string sTR1;
sTR1 = cCharToStr1;

char* cCharToStr2 = new char[20];
cCharToStr2 = "chartostr2";
string sTR2;
sTR2 = cCharToStr2;

/****************************************************/
/* string 转化到 char                               */
/****************************************************/
string sStrToChar1 = "strtochar1";
char cStrToChar1[20];
strcpy_s(cStrToChar1,sStrToChar1.data());

string sStrToChar2 = "strtochar2";
char cStrToChar2[20];
strcpy_s(cStrToChar2,sStrToChar2.c_str());

string sStrToChar3 = "strtochar3";
char cStrToChar3[20];
sStrToChar3._Copy_s(cStrToChar3,20,sStrToChar3.length(),0);
cStrToChar3[sStrToChar3.length()] = '\0';

/****************************************************/
/* string 转化到 CString                            */
/****************************************************/
string sStrToCStr1 = "sStrToCStr1" ;
CString csCStr1;
csCStr1 = sStrToCStr1.c_str();
//	csCStr1.Format(_T("%s"),sStrToCStr1.c_str());		//多字符集下可以用该行

/****************************************************/
/* CString 转化到 string                            */
/****************************************************/
CString csCStrToStr1 = _T("csCStrToStr1");
wstring sCStrToStr1 ;
sCStrToStr1 = csCStrToStr1.GetBuffer(csCStrToStr1.GetLength());
csCStrToStr1.ReleaseBuffer();

CString csCStrToStr2 = _T("csCStrToStr2");
string sCStrToStr2 ;

//****************************************************/
//* CString 转化到 char                              */
//****************************************************/
CString csCStrToChar1 = _T("csCStrToChar1");
char cCStrToChar1[20] ;
char *temp;
temp = T2A(csCStrToChar1);
strcpy_s(cCStrToChar1,temp);

CString csCStrToChar2 = _T("csCStrToChar2");
char cCStrToChar2[20] ;
int n = csCStrToChar2.GetLength();
int len = WideCharToMultiByte(CP_ACP,0,csCStrToChar2,csCStrToChar2.GetLength(),NULL,0,NULL,NULL);
WideCharToMultiByte(CP_ACP,0,csCStrToChar2,csCStrToChar2.GetLength()+1,cCStrToChar2,len,NULL,NULL);
cCStrToChar2[len] = '\0';

//****************************************************/
//* char 转化到 CString                              */
//****************************************************/
char cCharToCStr1[20] = "cCharToCStr1";
CString csCharToCStr1;
int charlen = strlen(cCharToCStr1);
len = MultiByteToWideChar(CP_ACP,0,cCharToCStr1,charlen,NULL,0);
TCHAR *buf = new TCHAR[len + 1];
MultiByteToWideChar(CP_ACP,0,cCharToCStr1,charlen,buf,len);
buf[len] = _T('\0');
csCharToCStr1 = buf;

char cCharToCStr2[20] = "cCharToCStr2";
CString csCharToCStr2;
csCharToCStr2 = A2T(cCharToCStr2);

char cCharToCStr3[20] = "cCharToCStr3";
CString csCharToCStr3;
csCharToCStr3 = (CString)cCharToCStr3;

//****************************************************/
//* char 转化到 int				      */
//****************************************************/
char cCharToInt1[10] = "123456";
int iCharToInt1;
iCharToInt1 = atoi(cCharToInt1);
char a = cCharToInt1[2];
iCharToInt1 = a - 0x30;

//****************************************************/
//* int  转化到 char                                 */
//****************************************************/
int iIntToChar1 = 13456;
char cIntToChar1[10];
sprintf_s(cIntToChar1,10,"%d",iIntToChar1);

int iIntToChar2 = 123456;
char cIntToChar2[10];
_itoa_s(iIntToChar2,cIntToChar2,10,10);

//****************************************************/
//* int  转化到 CString                              */
//****************************************************/
int iIntToCStr1 = 123456;
CString csIntToCStr1;
csIntToCStr1.Format(_T("%d"),iIntToCStr1);

//****************************************************/
//* CString  转化到 int                              */
//****************************************************/
CString csCStrToInt1 = _T("123456");
int iCStrToInt1;
iCStrToInt1 = _ttoi(csCStrToInt1);

//****************************************************/
//* CString  转化到 WCHAR                            */
//****************************************************/
CString str = _T("str");
WCHAR temp1[10];
wcscpy_s(temp1,str.GetLength()+1,str.GetBuffer(str.GetLength()));
temp1[5] = str[1];

cout<<"hello"<<endl;

char name[10] = "abc" ;
char sport[10] ;
const char* cSport = sport;

string na;
na = name;
str = "cstring";
char *p = (LPSTR)(LPCTSTR)str;
char pstr[10];
strcpy_s(pstr,10,p);
//	cSport = na.data();
strcpy_s(sport,na.c_str());
strcpy_s(sport+4,10,"123");

system("pause");
return 0;
}


转述其他



慎用USES_CONVERSION


USES_CONVERSION是ATL中的一个宏定义。用于编码转换(用的比较多的是CString向LPCWSTR转换)。在ATL下使用要包含头文件#include "atlconv.h"

使用USES_CONVERSION一定要小心,它们从堆栈上分配内存,直到调用它的函数返回,该内存不会被释放。如果在一个循环中,这个宏被反复调用几万次,将不可避免的产生stackoverflow。

在一个函数的循环体中使用A2W等字符转换宏可能引起栈溢出。

#include <atlconv.h>

void fn()

{

while(true)

{

{

USES_CONVERSION;

DoSomething(A2W("SomeString"));

}

}

}

让我们来分析以上的转换宏

#define A2W(lpa) (\

((_lpa = lpa) == NULL) ? NULL : (\

_convert = (lstrlenA(_lpa)+1),\

ATLA2WHELPER((LPWSTR) alloca(_convert*2), _lpa, _convert)))

#define ATLA2WHELPER AtlA2WHelper

inline LPWSTR WINAPI AtlA2WHelper(LPWSTR lpw, LPCSTR lpa, int nChars, UINT acp)

{

ATLASSERT(lpa != NULL);

ATLASSERT(lpw != NULL);

// verify that no illegal character present

// since lpw was allocated based on the size of lpa

// don't worry about the number of chars

lpw[0] = '\0';

MultiByteToWideChar(acp, 0, lpa, -1, lpw, nChars);

return lpw;

}

关键的地方在 alloca 内存分配内存上。

#define alloca _alloca

_alloca

Allocates memory on the stack.

Remarks

_alloca allocates size bytes from the program stack. The allocated space is automatically freed when the calling function

exits. Therefore, do not pass the pointer value returned by _alloca as an argument to free.

问题就在这里,分配的内存是在函数的栈中分配的。而VC编译器默认的栈内存空间是2M。当在一个函数中循环调用它时就会不断的分配栈中的内存。

以上问题的解决办法:

1、自己写字符转换函数,不要偷懒

Function that safely converts a 'WCHAR' String to 'LPSTR':

char* ConvertLPWSTRToLPSTR (LPWSTR lpwszStrIn)

{

LPSTR pszOut = NULL;

if (lpwszStrIn != NULL)

{

int nInputStrLen = wcslen (lpwszStrIn);

// Double NULL Termination

int nOutputStrLen = WideCharToMultiByte (CP_ACP, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0) + 2;

pszOut = new char [nOutputStrLen];

if (pszOut)

{

memset (pszOut, 0x00, nOutputStrLen);

WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, pszOut, nOutputStrLen, 0, 0);

}

}

return pszOut;

}

等等一个一个的实现。

2、把字符转换部分放到一个函数中处理。

void fn2()

{

USES_CONVERSION;

DoSomething(A2W("SomeString"));

}

void fn()

{

while(true)

{

fn2();

}

}

如果不知道这点问题,在使用后崩溃时很难查出崩溃原因的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: