2020年1月17日 星期五

Visual Studio C++ std::string std::wstring utf8 UTF-8


Using (MT5)

// convert UTF-8 string to wstring
std::wstring utf8_to_wstring (const std::string& str)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
    return myconv.from_bytes(str);
}

// convert wstring to UTF-8 string
std::string wstring_to_utf8 (const std::wstring& str)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
    return myconv.to_bytes(str);
}

CHAR 936 to UTF8 (MT4)
https://blog.csdn.net/WU9797/article/details/96124105

std::string GBToUTF8Ex(const char *input) {
if (!input || strlen(input) < 1)
return "";
std::stringstream ss;
int len = MultiByteToWideChar(936, 0, input, -1, NULL, 0);
wchar_t *wstr = new wchar_t[len + 1];
memset(wstr, 0, len + 1);
MultiByteToWideChar(936, 0, input, -1, wstr, len);
len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
char *str = new char[len + 1];
memset(str, 0, len + 1);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
ss << str;
delete[]wstr;
delete[]str;
return ss.str();
}


Someone's method does not work for me
inline std::string charsetToUtf8String(const std::string & string) {
int wchars_num = MultiByteToWideChar(936, 0, string.c_str(), -1, NULL, 0);
std::wstring wResult(wchars_num, ' ');
// charset 936 = Chinese Simplified (GB2312)
MultiByteToWideChar(936, 0, string.c_str(), -1, &wResult[0], wchars_num);
return toString(wResult);
}

inline std::string toString(const std::wstring & wstring) {
return utility::conversions::utf16_to_utf8(wstring);
}

沒有留言:

張貼留言

2023 Promox on Morefine N6000 16GB 512GB

2023 Promox on Morefine N6000 16GB 512GB Software Etcher 100MB (not but can be rufus-4.3.exe 1.4MB) Proxmox VE 7.4 ISO Installer (1st ISO re...