首页 > 代码库 > 基本字符类型的转换

基本字符类型的转换

一、int <---> CString

  int转CString:

    int i=100;

    CString str="";

    str.Format("%d",i);

  CString转int:

    CString str="123";

    int i;

    i=atoi(str);

    //i=_ttoi(str);

二、float <---> CString

  float转CString:

    float a=3.1415;

    CString str="";

    str.Format("%.2f",a); //保留小数点后两位

  CString转float:

    先将CString转char*,因为atof()的参数为char*型,atof()的返回值为double型,可直接强转为float型;

    CString str="3.1415";

    char* s;

    s=str.GetBuffer(str.GetLength());

    str.ReleaseBuffer();

    float f;

    f=atof(s);

三、double <---> CString

  double转CString:

    double d=3.1415;

    CString str="";

    str.Format("%.2lf",d);

  CString转double:

    CString str="3.1415";

    char* s;

    s=str.GetBuffer(str.GetLength());

    str.ReleaseBuffer();

    double d;

    d=atof(s);

四、string <---> CString

  string转CString:

    CString str;

    string s="hello";

    str.Format("%s",s.c_str());

  CString转string:

    CString str="hello";

    string s(str.GetBuffer());

五、char* <---> CString

  char*转CString:

    char sChar[]="hello";

    CString str;

    str.Format("%s",sChar);

    AfxMessageBox(str);

  CString转char*:

    方法一:

    CString str="hello";

    char* s;

    s=new char[str.GetLength()+1];

    strcpy(s,str);

    方法二:

    CString str="hello";

    char* s;

    s=str.GetBuffer(str.GetLength());

    str.ReleaseBuffer();

六、TCHAR* <---> CString

  TCHAR*转CString:

    TCHAR sChar[]="hello";

    CString str;

    str.Format("%s",sChar);

    AfxMessageBox(str);

  CString转TCHAR*:

    方法一:

    CString str="hello";

    TCHAR* s=(LPTSTR)(LPCTSTR)str;

    方法二:

    CString str="hello";

    TCHAR* s;

    s=new TCHAR[str.GetLength()+1];

    _tcscpy(s,str);

    方法三:

    CString str="hello";

    TCHAR* s;

    s=str.GetBuffer(str.GetLength());

    str.ReleaseBuffer();

七、int <---> char*

  int转char*:

    int i=54321;

    char ch[5];

    itoa(i,ch,10);  //10-十进制,2-二进制,8-八进制,16-十六进制

 

基本字符类型的转换