string与CString,int,char[],char*之间的转换

来源:互联网 发布:程序员写博客写什么 编辑:程序博客网 时间:2024/06/04 19:58

string是c++中的字符串格式,其重载了许多运算符号+-<>等,使用起来最为灵活,包含在<string>中,在c++编程可以作为各种字符串类型的中转类型。

CString是Visual Studio下的字符串格式,并不通用,经常需要转换,而且MFC不能跨平台,所以代码不具有可移植性,因此可以用string来代替和中转:

CString 与 string 相互转换,可以使用Visual Studio(2015)下的宏函:

CString cst1="hello",cst2;
string st1="hello",st2;

CString ->string
st2=CT2A(cst1);

string->CString
cst2=CA2T(st1);


对于将int,double,float等转换成string,只需用到c++里的全局函数to_string()就可以了,各种格式都可以,举例:

string to_string (int val);

string to_string (unsigned long val);


char[]是字符数组,固定大小的;char*也是字符串形式,可以直接给string赋值:

char ch[20]="hello!"; string str=ch;

char* ch="hello!"; string str=ch;


string转char*,两者相同,只需要传递地址就行;

string str="hello!";转换为char * 类型;

const char * mystr=str.c_str();  注意要加上const,因为传递的时指针,不能被修改






原创粉丝点击