// UTF8字符串转成Window下可识别字符串
std::string utf8_to_str(const std::string& str)
{int nwLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);wchar_t* pwBuf = new wchar_t[nwLen + 1];//加1用于截断字符串 memset(pwBuf, 0, nwLen * 2 + 2);MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), pwBuf, nwLen);int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);char* pBuf = new char[nLen + 1];memset(pBuf, 0, nLen + 1);WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);std::string retStr = pBuf;delete[]pBuf;delete[]pwBuf;pBuf = NULL;pwBuf = NULL;return retStr;
}// Window下字符串转成json识别的UTF8字符串
std::string str_to_utf8(const std::string& str)
{int nwLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);wchar_t* pwBuf = new wchar_t[nwLen + 1];//加1用于截断字符串 ZeroMemory(pwBuf, nwLen * 2 + 2);::MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), pwBuf, nwLen);int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);char* pBuf = new char[nLen + 1];ZeroMemory(pBuf, nLen + 1);::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);std::string retStr(pBuf);delete[]pwBuf;delete[]pBuf;pwBuf = NULL;pBuf = NULL;return retStr;
}
测试示例:
int main()
{// read filestd::ifstream ifs("file.json");json js;ifs >> js;ifs.close();std::string strName = js["name"];std::string str = utf8_to_str(strName);str += "+新中文测试";js["name"] = str_to_utf8(str);// write filestd::ofstream ofs("newfile.json");ofs << std::setw(4) << js << std::endl;ofs.close();return 0;
}
file.json文件内容:
{"name": "2023年08月03日+中文测试","object": {"key1": "test","key2": 123.4},"pi": 3.141
}
newfile.json文件内容:
{"name": "2023年08月03日+中文测试+新中文测试","object": {"key1": "test","key2": 123.4},"pi": 3.141
}