Window下wchar_t与char字符串之间的转换

时间:2023-01-24 19:35:19
 1 static std::string WChar2Ansi(const wchar_t* src) {
 2     std::string ret = "";
 3     const auto size = WideCharToMultiByte(CP_ACP, 0, src, -1, nullptr, 0, nullptr, nullptr);
 4     if (size > 0) {
 5         char* dest = new char[size];
 6         if (nullptr != dest) {
 7             WideCharToMultiByte(CP_ACP, 0, src, -1, dest, size, nullptr, nullptr);
 8             ret = dest;
 9             delete[] dest;
10         }
11     }
12     return ret;
13 }
14 
15 static std::wstring Ansi2WChar(const char* src) {
16     std::wstring ret = L"";
17     const auto size = MultiByteToWideChar(CP_ACP, 0, src, -1, nullptr, 0);
18     if (size > 0) {
19         wchar_t* dest = new wchar_t[size];
20         if (nullptr != dest) {
21             MultiByteToWideChar(CP_ACP, 0, src, -1, dest, size);
22             ret = dest;
23             delete[] dest;
24         }
25     }
26     return ret;
27 }
 1 int main() {
 2     std::wcout.imbue(std::locale("chs"));
 3 
 4     const char* str = "*你好abc123#";
 5     const wchar_t* wstr = L"*你好abc123#";
 6 
 7     auto dest1 = WChar2Ansi(wstr);
 8     auto wdest2 = Ansi2WChar(str);
 9 
10     std::cout << "S1: " << dest1 << std::endl;
11     std::wcout << L"S2: "<<wdest2 << std::endl;
12 
13     return 0;
14 }

测试环境:Windows 7 and VS2015

以后需要就来这里copy。再也不想写这样的代码了QAQ。

另外补充:如果想在控制台中用std::wcout输出中文,需要先加一句“ std::wcout.imbue(std::locale("chs")); ” 进行设定。

更多信息可以查看这里:https://blog.csdn.net/dahaiyudong/article/details/82533574