简体   繁体   中英

utf8 and utf16 conversion

I have a wchar_t string, for example, L"hao123--我的上网主页", I can convert it to utf8

encoding, the output string is "hao123锛嶏紞鎴戠殑涓婄綉涓婚〉", but finally, I must write this

string to a plain text file, its format is utf16 (I know this from others), "hao123\-\-\我\的\上\网\主\页".

Because I must save it in C++ std string and then write it to a file, How can I convert

"hao123锛嶏紞鎴戠殑涓婄綉涓婚〉" to "hao123\-\-\我\的\上\网\主\页" in char or C++ std string ?

Can anyone give me some tips?

Thanks in advance!

In C++11 this can be done with:

#include <locale>
#include <codecvt>
#include <string>
#include <iostream>

int main()
{
    std::wstring_convert<std::codecvt_utf16<wchar_t> > myconv;
    std::wstring ws(L"hao123--\x6211\x7684\x4E0A\x7F51\x4E3B\x9875");
    std::string bs = myconv.to_bytes(ws);
    std::cout << bs << '\n';
}

我自己编写了转换函数,有关更多信息,请访问C ++ Unicode UTF-16编码

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM