Unicode is a 16-bit character encoding, providing enough encodings for all languages. All ASCII characters are included in Unicode as widened characters.
A char * string (also known as a C style string) uses a null character to indicate the end of the string. C style strings usually require one byte per character, but can also use two bytes. In the examples below, char * strings are sometimes referred to as multibyte character strings because of the string data that results from converting from Unicode strings.
// Create and display a C style string, and then use it // to create different kinds of strings. char *orig = "Hello, World!"; cout << orig << " (char *)" << endl; // newsize describes the length of the // wchar_t string called wcstring in terms of the number // of wide characters, not the number of bytes. size_t newsize = strlen(orig) + 1; // The following creates a buffer large enough to contain // the exact number of characters in the original string // in the new format. If you want to add more characters // to the end of the string, increase the value of newsize // to increase the size of the buffer. wchar_t * wcstring = new wchar_t[newsize]; // Convert char* string to a wchar_t* string. size_t convertedChars = 0; mbstowcs_s(&convertedChars, wcstring, newsize, orig, _TRUNCATE); // Display the result and indicate the type of string that it is. wcout << wcstring << _T(" (wchar_t *)") << endl;
errno_t mbstowcs_s( size_t *pReturnValue, wchar_t *wcstr, size_t sizeInWords, const char *mbstr, size_t count );
mbstowcs_s uses the current locale for any locale-dependent behavior; _mbstowcs_s_l is identical except that it uses the locale passed in instead.
// 計算輸入(欲轉換)字串 pszValue 的字數 (character)。注意! 非字節數 (byte)。 size_t n = ::MultiByteToWideChar(CP_ACP,0,(const char *)pszValue,-1,NULL,0); // 配置輸出(欲轉出)字串緩衝區。 wchar_t* buffer = new wchar_t[n]; // 轉換輸入字串 (pszValue) 至輸出字串緩衝區 (buffer)。 ::MultiByteToWideChar(CP_ACP,0,(const char *)pszValue,-1,buffer,int(n)); // 將緩衝區資料另存起來。 m_strValue = tstring(buffer); // 釋放緩衝區。 delete [] buffer;
int MultiByteToWideChar( _In_ UINT CodePage, _In_ DWORD dwFlags, _In_ LPCSTR lpMultiByteStr, _In_ int cbMultiByte, _Out_opt_ LPWSTR lpWideCharStr, _In_ int cchWideChar );
#include <sstream> #include "tstring.h" std::wstringstream wss; wss << pszValue; m_strValue = tstring(wss.str().c_str());