C/C++ 调用标准库函数实现 std::string to std::wstring 相互字符集变换(转)
转自:https://blog.csdn.net/liulilittle/article/details/127697458
#include <locale> #include <codecvt> #include <string> #include <vector> #if _MSC_VER >= 1600 #pragma execution_character_set("utf-8") #endif std::wstring utf8_to_wstring(const std::string& s) { std::wstring_convert<std::codecvt_utf8<wchar_t>> converter; return converter.from_bytes(s); } std::string wstring_to_utf8(const std::wstring& s) { std::wstring_convert<std::codecvt_utf8<wchar_t>> converter; return converter.to_bytes(s); } std::wstring ascii_to_wstring(const std::string& s) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; return converter.from_bytes(s); } std::wstring ascii_to_wstring2(const std::string& s) { std::size_t len = mbstowcs(NULL, s.data(), 0); if (len == 0 || len == std::string::npos) { return std::wstring(); } std::vector<wchar_t> buf(len + 1); return std::wstring(buf.data(), mbstowcs(&buf[0], s.data(), buf.size())); } std::string wstring_to_ascii(const std::wstring& s) { std::size_t len = wcstombs(NULL, s.data(), 0); if (len == 0 || len == std::string::npos) { return std::string(); } std::vector<char> buf(len + 1); return std::string(buf.data(), wcstombs(&buf[0], s.data(), buf.size())); } int main(int argc, const char* argv[]) { setlocale(LC_ALL, "chs"); _wsetlocale(LC_ALL, L"chs"); wprintf(L"%s\n", ascii_to_wstring(wstring_to_ascii(L"中国")).data()); return getchar(); }
----------