VC++中一些常用的数据类型之间的相互转化
最后更新于:2022-04-01 20:34:47
在编程的过程中,往往会涉及到一些常见的数据类型之间的相互转化,到网上一查,大家真是众说风云,让人甚是眼花缭乱,找了半天也找不到自己想要的答案。下面结合实例详细说明几种数据类型之间的转换方法(**完整的实例程序可在我的CSDN资源中下载:[http://download.csdn.net/detail/margin1988/4241292](http://download.csdn.net/detail/margin1988/4241292)**):
(1)CString -> int
~~~
CString intStr="100";
int a;
a = _ttoi(intStr);
~~~
(2)int -> CString
~~~
CString aStr;
aStr.Format("%d",a);
~~~
(3)CString -> double
~~~
CString doubleStr="3.1415926";
double b;
b = atof(doubleStr.GetBuffer(0));
~~~
(4)double -> CString
~~~
CString bStr;
bStr.Format("%0.4f",b);//保留小数点后4位
~~~
(5)CString -> LPCSTR
~~~
LPCSTR lpcStr;
CString cStr;
int c=1389;
cStr.Format("%d",c);
lpcStr = _T(cStr);
~~~
(6)LPCSTR -> CString
~~~
CString dStr;
dStr = lpcStr;
~~~
(7)char* -> CString
~~~
char* cha1="你好";
CString str1;
str1 = cha1;//str1.Format("%s",cha1);
~~~
(8)CString -> char*
~~~
CString str2;
char* cha2;
str2.Format("很好");
cha2 = str2.GetBuffer(0);
~~~
(9)char -> CString
~~~
char ch = 'a';
CString str3;
str3.Format("%c",ch);
~~~
(10)string -> const char*
~~~
string s = "你好";
const char* cha3;
cha3 = s.c_str();
~~~
(11)CString -> wchar_t
~~~
wchar_t wStr[256];
CString str0;
str0 = "姓名";
MultiByteToWideChar(CP_ACP, 0, str0, -1, wStr, 256);
~~~
(12) wchar_t -> CString
~~~
wchar_t wStr[256];
CString str0;
int size;
char *ch;
size=WideCharToMultiByte(CP_ACP,0,sheet->Cell(i,1)->GetWString(),-1,NULL,0,NULL,NULL);
ch=new char[size+1];
WideCharToMultiByte(CP_ACP,0,sheet->Cell(i,1)->GetWString(),-1,ch,size,NULL,NULL);
str0.Format("%s",ch);
size = 0;
delete[] ch;
~~~
';