char、wchar_t、ACHAR、WCHAR、TCHAR

时间:2021-03-10 20:17:11

最近用到上面几种不同的字符类型,下面贴上在网上收集到的资料。 

1、char

单字节变量类型,最多表示256个字符。

2、wchar_t

宽字节变量类型,用于表示Unicode字符,它实际定义在<string.h>里:typedef unsigned short wchar_t。 

定义宽字节类型方法如下:

char、wchar_t、ACHAR、WCHAR、TCHARwchar_t c = `A ' ;
char、wchar_t、ACHAR、WCHAR、TCHAR
wchar_t * p = L " Hello! " ;
char、wchar_t、ACHAR、WCHAR、TCHARwchar_t a[]
= L " Hello! " ;

其中,宽字节类型每个变量占用2个字节。

 

3、ACHAR

此类型是AUTODESK公司在AdAChar.h 头文件中定义的,当定义了AD_UNICODE(AUTODESK公司使用UNICODE宏)时为wchar_t。

4、WCHAR

在头文件中有这样的定义:typedef wchar_t WCHAR; 所以WCHAR实际就是wchar_t。 

5、TCHAR

 如果定义了UNICODE宏则TCHAR被定义为wchar_t,typedef wchar_t TCHAR; 否则TCHAR被定义为char typedef char TCHAR;

6、string、wstring
        string和wstring均定义在string头文件中,其中string类型变量中每个单元为char型字符,wstring为wchar_t型字符。

7、相互转化

//char* to string :
char、wchar_t、ACHAR、WCHAR、TCHAR
char *a = "abcde";
char、wchar_t、ACHAR、WCHAR、TCHAR
string str = a;
char、wchar_t、ACHAR、WCHAR、TCHAR
//string to char*
char、wchar_t、ACHAR、WCHAR、TCHAR
char *a = str.c_str();
char、wchar_t、ACHAR、WCHAR、TCHAR
//wchar_t* to wstring
char、wchar_t、ACHAR、WCHAR、TCHAR
wchar_t *b = L"abcde";
char、wchar_t、ACHAR、WCHAR、TCHARwstring wstr
= b;
char、wchar_t、ACHAR、WCHAR、TCHAR
//wstring to wchar_t*
char、wchar_t、ACHAR、WCHAR、TCHAR
wchar_t *b = wstr.c_str();

 

//ACHAR to string

 string ACharToString(const ACHAR * inAchar)

{

int len = (int)wcslen(inAchar);

string strBuffer;
 int nCopied = WideCharToMultiByte(CP_OEMCP,WC_COMPOSITECHECK,inAchar,len,NULL,0,NULL,NULL );

 if( nCopied <= 0 )
  return strBuffer;
 strBuffer.resize( nCopied );
 WideCharToMultiByte(CP_OEMCP,WC_COMPOSITECHECK, inAchar,len,const_cast<LPSTR>(strBuffer.data()),nCopied,NULL,NULL);
 return strBuffer;

}

 

// string to ACHAR

ACHAR * StringToAChar(const string inString)

{

const char* orig = inString.c_str();
 size_t origsize = strlen(orig) + 1; 
 size_t convertedChars = 0;

 ACHAR *wcstring = (ACHAR *)malloc(origsize*2+1);
 mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);
 return wcstring;

} 

 

//string to wstring
wstring stringToWstring(const std::string& s)

{


 setlocale(LC_ALL, "chs");
 const char* _Source = s.c_str();
 size_t _Dsize = s.size() + 1;
 wchar_t *_Dest = new wchar_t[_Dsize];
 wmemset(_Dest, 0, _Dsize);
 mbstowcs(_Dest,_Source,_Dsize);
 std::wstring result = _Dest;
 delete []_Dest;
 setlocale(LC_ALL, "C");
  return result;

 

//wstring to string 

string wStringToString(const std::wstring& ws)

{

 std::string curLocale = setlocale(LC_ALL, NULL);     
 setlocale(LC_ALL, "chs");
 const wchar_t* _Source = ws.c_str();
 size_t _Dsize = 2 * ws.size() + 1;
 char *_Dest = new char[_Dsize];
 memset(_Dest,0,_Dsize);
 wcstombs(_Dest,_Source,_Dsize);
 std::string result = _Dest;
 delete []_Dest;
 setlocale(LC_ALL, curLocale.c_str());

 return result;

}