c++中的一些类型转换 : CString,string,int ,long,double,char*,const char*,date等 .
原文出自:http://blog.sina.com.cn/s/blog_6e7fed390100xiiz.html |
在c/c++开发过程中总遇到那种类型转换的问题,很令人头疼,百度到这篇文章后,感觉不错就转载了,感谢作者的辛勤劳作。
1. char* to string
string s(char *);
注:在不是初始化的地方最好用assign().
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
2. string to const char*
string a="strte";
const char* r=a.c_str();
注意是const的。还要转到char*:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2.2. const char* to char*
const char* r="123";
char
strcpy(p1,r);
附:http://hi.baidu.com/cfans/blog/item/06970ef4b671f366dcc4745d
·············································································································
3. cstring to string
vs2005 Unicode下:
非Unicode下:
CString cs("test");
std::string str=cs.getBuffer(0);
cs.ReleaseBuffer();
注:GetBuffer()后一定要ReleaseBuffer(),否则就没有释放缓冲区所占的空间.
++++++++++++++++++++++++++++++++++++++++++++++++++++
4. double ,int to string
#include <sstream>
using namespace std;
stringstream ss;
string result;
long n=11111;
stream << n; //从long型数据输入
stream >>result; //转换为 string
===================================================
5.char*
char *s; double x; int i; long l;
s = " -2309.12E-15";
x = atof( s );
printf( "atof test: ASCII string: %s/tfloat: %e/n", s, x );
s = "7.8912654773d210";
x = atof( s );
printf( "atof test: ASCII string: %s/tfloat: %e/n", s, x );
s = " -9885 pigs";
i = atoi( s );
printf( "atoi test: ASCII string: %s/t/tinteger: %d/n", s, i );
s = "98854 dollars";
l = atol( s );
printf( "atol test: ASCII string: %s/t/tlong: %ld/n", s, l );
------------------------------------------------------------------------------------------------
6. string to int ,long,double
——————————————————————————————————————————
7. date to string
#include <time>
using namespace std;
char dateStr [9];
char timeStr [9];
printf( "The current date is %s /n", dateStr);
_strtime( timeStr );
printf( "The current time is %s /n", timeStr);
--------实践证明是正确的版本--------------------------------------------------------------
#include <iostream>
#include <ctime>
#include <cerrno>
int main()
{
}
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
8.string to cstring
+++++++++++++++++++++++++++++++++++++++++++++++++++++
非Unicode下:
int 转 CString:
CString.Format("%d",int);
...............................
string 转 CString
CString.format("%s", string.c_str());
用c_str()确实比data()要好.
.......................................
char* 转 CString
CString.format("%s", char*);
.....................................................
CString 转 int
...................................................................................................................................
9.在Unicode下的CString to double
CSting sTemp("123.567");
double dTemp = _wtof(sTemp.GetString());