utf8和utf16转换

发布于 2024-08-29 16:35:42 字数 391 浏览 3 评论 0原文

我有一个wchar_t字符串,例如L“hao123--我的上网主页”,我可以将其转为utf8

编码,输出的字符串是“hao123锛嶏紞鎴戠殑黎婄绣黎婚〉”,但最后,我必须把这个

字符串写入一个纯文本文件,它的格式是utf16(我从别人那里知道的),“hao123\uFF0D\uFF0D\u6211\u7684\u4E0A\u7F51\u4E3B\u9875”。

因为我必须将其保存在C++ std字符串中,然后将其写入文件,如何将

“hao123锛嶏紞鎴戠殑六婄绣三婚〉”转换为“hao123\uFF0D\uFF0D\u6211\u7684\u4E0A\” u7F51\u4E3B\u9875" 在 char 或 C++ 标准字符串中?

谁能给我一些建议吗?

提前致谢!

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\uFF0D\uFF0D\u6211\u7684\u4E0A\u7F51\u4E3B\u9875".

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

"hao123锛嶏紞鎴戠殑涓婄綉涓婚〉" to "hao123\uFF0D\uFF0D\u6211\u7684\u4E0A\u7F51\u4E3B\u9875" in char or C++ std string ?

Can anyone give me some tips?

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

回首观望 2024-09-05 16:35:42

在 C++11 中,这可以通过以下方式完成:

#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';
}

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';
}
将军与妓 2024-09-05 16:35:42

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

I wrote on conversion function by myself, for more information, please visit C++ unicode UTF-16 encoding

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文