初學C/C++,char, wchar_t, TCHAR, ACHAR, _T()這幾個類型的差異和聯系曾經讓我很是頭疼,在此做一下簡單的歸納總結,希望能給各位剛入門的菜菜們一點幫助。

char :

單字節變量類型,最多表示256個字符,在ANSI C中包括:26 lowercase letters, 26 uppercase letters, 10 digits, 32 symbols, 33 control codes, and a space, for a total of 128 codes.

wchar_t :

寬字節變量類型,用于表示Unicode字符,它實際定義在<string.h>里:typedef unsigned short wchar_t。

定義寬字節類型方法如下:
wchar_t c = `A' ; 
wchar_t * p = L"Hello!" ; 
wchar_t a[] 
= L"Hello!" ; 
其中,寬字節類型每個變量占用2個字節,故上述數組a的sizeof(a) = 14。

TCHAR / _T( ) :

TCHAR.H provides a set of alternative names for the normal run-time library functions requiring string parameters (for example, _tprintf and _tcslen). These are sometimes referred to as "generic"function names because they can refer to either the Unicode or non-Unicode versions of the functions. TCHAR.H also solves the problem of the two character data types with a new data type named TCHAR.

如果在程序中既包括ANSI又包括Unicode編碼,需要包括頭文件tchar.h。TCHAR是定義在該頭文件中的宏,它視你是否定義了_UNICODE宏而定義成:
定義了_UNICODE:    typedef wchar_t TCHAR ;
沒有定義_UNICODE: typedef char TCHAR ;

_T( )也是定義在該頭文件中的宏,視是否定義了_UNICODE宏而定義成:
定義了_UNICODE:    #define _T(x)  L##x
沒有定義_UNICODE: #define _T(x)  x

注意:如果在程序中使用了TCHAR,那么就不應該使用ANSI的strXXX函數或者Unicode的wcsXXX函數了,而必須使用tchar.h中定義的_tcsXXX函數。

以strcpy函數為例子,總結一下:

//如果你想使用ANSI字符串,那么請使用這一套寫法:
char szString[100];
strcpy(szString,
"test");
//如果你想使用Unicode字符串,那么請使用這一套:
wchar_t szString[100];
wcscpy(szString,L
"test");
//如果你想通過定義_UNICODE宏,而編譯ANSI或者Unicode字符串代碼:
TCHAR szString[100];
_tcscpy(szString,_TEXT(
"test"));

string / wstring :

string和wstring均定義在string頭文件中,其中string類型變量中每個單元為char型字符,wstring為wchar_t型字符。
定義方法如下:
string str("abcd");
wstring wstr(L"中國人");

各轉換方法:
//char* to string : 
char *= "abcde";
string str = a;

//string to char*
char *= str.c_str();

//wchar_t* to wstring
wchar_t *= L"abcde";
wstring wstr 
= b;

//wstring to wchar_t*
wchar_t *= wstr.c_str();

//wstring to string 
std::string ws2s(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;
}


//string to wstring
std::wstring s2ws(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;
}