ObjextARX-VS2005-字符串转换
1.使用string必须添加头文件
#include"string"
using namespace std;
2.使用CString必须添加头文件(在非MFC工程中)
#include"afx.h"
注意:当出现#error : Building MFC application with /MD[d] (CRT
dll version) requires MFC shared dll version. Please #define
_AFXDLL or do not use /MD[d]错误时,改工程设置:
Project|Properties|Configuration Properties|General|Use of MFC :
Use MFC in a Shared DLL(项目-〉属性-〉use of MFC 改成use MFC in a
share dll)
3.wchar_t
wchar_t是C++的字符数据类型,char是8位字符类型,最多只能包含256种
字符,许多外文字符集所含的字符数目超过256个,字符型无法表示
wchar_t数据类型为16位,所能表示的字符数远超char型。
4.ACHAR类型(此类型是AUTODESK公司在adachar.h 头文件中定义的-
typedef wchar_t ACHAR;)
#include "adachar.h"
5.USES_CONVERSION在atlconv.h头文件中定义
#include "atlconv.h "
6.string->ACHAR*
string str="string";
ACHAR* ach;
USES_CONVERSION;
ach=(ACHAR*)A2CT(str.c_str());
-
std::string str="something";
-
TCHAR *param=new TCHAR[str.size()+1];
-
param[str.size()]=0;
-
//As much as we'd love to, we can't use memcpy() because
-
//sizeof(TCHAR)==sizeof(char) may not be true:
-
std::copy(str.begin(),str.end(),param);
7.ACHAR*->string
ACHAR* ach;
USES_CONVERSION;
string temp=W2A(ach);
8.(wchar_t)ACHAR*->char*
char * ch;
ACHAR* ach;
USES_CONVERSION;
ch=T2A(ach);
9.char*->ACHAR*
ACHAR* ach1;
char * ch;
方法一:
USES_CONVERSION;
ach1=A2W(ch);
方法二:
size_t convertedChars=0;//记录返回实际转换字符串的长度
mbstowcs_s(&convertedChars,ach1,10,ch,_TRUNCATE);//10为ch的最大长
度,随着需要而改变
10.int->string
string str;
int nNumber=10001;
char cT[10];//把int转化为string
_itoa_s(nNumber,cT,10);
str=cT;或string str(cT);
11.string->int
12.CString->char*
方法一:
char* ch;
CString temp;
ch=T2A(temp.GetBuffer(0));
方法二:
使用强制转换
CString theString( "This is a test" );
LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString;
13.char*->CString
方法一:
可以直接赋值
CString cstr;
char* ch;
cstr=ch;
方法二:
通过使用Format函数
char chArray[] = "This is a test";
CString cstr;
MBCS下(即没定义UNICODE时):
cstr.Format(_T("%s"), chArray);
定义UNICODE时:
USES_CONVERSION;
cstr.Format(_T("%s"), A2W(chArray));
14.char*->int
char* ch;
int n=atoi(ch);
15.int->char*
int n=45;
char nCh[10];
char* ch;
itoa(n,nCh,16);//16为进制,可以取2,8,10,16等
也可以采用如下形式:ch=itoa(n,nCh,16);
VS2005环境用:_itoa_s(n,nCh,2);
16.CString->string
string str;
CString temp;
USES_CONVERSION;
str=T2A(temp.GetBuffer(0));
17.string->CString
CString cstr;
string str;
cstr=str.c_str();
18.char*->string
直接构造法:
char cT1[20];
string ste(cT1);//重新构造一个字符串
19.string->char*
string ste;
ch=(char*)ste.c_str();通过char*转换去掉const属性,注意ch只能为
char*,不能为char[]
20.float(double)->string
char cT1[20];
_gcvt_s(cT1,20,110.58485678,6);//6为精确度
string ste(cT1);
21.string->double
string num="15.12054";
double d=atof(num.c_str());