Conversion between wchar_t, Char, string, and wstring is required when processing Chinese characters.
The conversion between char and string, wchar_t and wstring is relatively simple, and the code passes the test under vs2010.
# Include <iostream> # include <string> # include <tchar. h> # include <windows. h> using namespace STD; // converting a wchar string to a ANSI stringchar * W2C (char * pcstr, const wchar_t * pwstr, size_t Len) {int nlength = wcslen (pwstr ); // obtain the converted length int nbytes = widechartomultibyte (0, 0, pwstr, nlength, null, 0, null); If (nbytes> Len) nbytes = Len; // use the preceding result to convert Unicode characters to ASCII characters widechartomultibyte (, pwstr, nlength, pcstr, nbytes, null, null); Return pcstr;} int main () {setlocale (lc_all, "CHS"); char * Cc = "this is a char test"; wchar_t * WCC = l "This Is A wchar test "; string STR ("this is a string test"); wstring wstr = l "This Is A wstring test"; // string to charconst char * char_test = Str. c_str (); // cout <"char_test:" <char_test <Endl; // Char to stringstring Ss = cc; // cout <"SS is: "<SS <Endl; // wstring to wcharconst wchar_t * wchar_test = wstr. c_str (); // wcout <wchar_test <Endl; // wchar to wstringwstring WSS = WCC; wcout <WCC <Endl; // Char to wchar_twchar_t * WC = new wchar_t [Str. size () + 1]; // swprintf (WC, l "% s", CC); // wcout <CC <Endl; Delete [] WC; // wchar_t to charchar * pcstr = (char *) malloc (sizeof (char) * (2 * wcslen (WCC) + 1); memset (pcstr, 0, 2 * wcslen (WCC) + 1); W2C (pcstr, WCC, 2 * wcslen (WCC) + 1); free (pcstr); System ("pause "); return 1 ;}