Skip to content

Instantly share code, notes, and snippets.

@lyandut
Last active March 3, 2022 04:34
Show Gist options
  • Save lyandut/ecec463224c614ad4286f77550994c4e to your computer and use it in GitHub Desktop.
Save lyandut/ecec463224c614ad4286f77550994c4e to your computer and use it in GitHub Desktop.
Encoding Conversion for C++ (deprecated in C++17).
#include <codecvt>
std::string name = "李研"; // GBK encoding
std::wstring w_name = string2wstring(name, ".936");
std::string utf8_name = wstring2utf8(w_name);
std::string wstring2utf8(const std::wstring & wstr) {
std::wstring_convert< std::codecvt_utf8<wchar_t> > cnv;
return cnv.to_bytes(wstr);
}
std::wstring utf82wstring(const std::string & str) {
std::wstring_convert< std::codecvt_utf8<wchar_t> > cnv;
return cnv.from_bytes(str);
}
std::string wstring2string(const std::wstring & wstr, const std::string & locale) {
typedef std::codecvt_byname<wchar_t, char, std::mbstate_t> F;
std::wstring_convert<F> cnv(new F(locale));
return cnv.to_bytes(wstr);
}
std::wstring string2wstring(const std::string & str, const std::string & locale) {
typedef std::codecvt_byname<wchar_t, char, std::mbstate_t> F;
std::wstring_convert<F> cnv(new F(locale));
return cnv.from_bytes(str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment