本文主要是介绍wstring_convert,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
char*和wchar_t*之间的相互转换。
W2A及A2W
要点:
- USES_CONVERSION;
- W2A及A2W
- 只能用在c++代码中。
代码:
#include
wstring_convert
参考: http://www.cplusplus.com/reference/locale/wstring_convert/
最新的C++编译器才行。
该链接中的代码示例:
// converting from UTF-32 to UTF-8
#include <iostream> // std::cout, std::hex
#include <string> // std::string, std::u32string
#include <locale> // std::wstring_convert
#include <codecvt> // std::codecvt_utf8
#include <cstdint> // std::uint_least32_tint main ()
{std::u32string str32 ( U"\U00004f60\U0000597d" ); // ni hao (你好)std::string str8;std::wstring_convert<std::codecvt_utf8<char32_t>,char32_t> cv;str8 = cv.to_bytes(str32);// print contents (as their hex representations):std::cout << std::hex;std::cout << "UTF-32: ";for (char32_t c : str32)std::cout << '[' << std::uint_least32_t(c) << ']';std::cout << '\n';std::cout << "UTF-8 : ";for (char c : str8)std::cout << '[' << int(static_cast<unsigned char>(c)) << ']';std::cout << '\n';return 0;
}
WideCharToMultiByte()
示例转换函数:
bool ws2s(const std::wstring& ws, std::string& s)
{const wchar_t* pws = ws.c_str();int iByte = WideCharToMultiByte(CP_OEMCP, 0, pws, -1, NULL, 0, NULL, NULL);if (iByte == 0) return false;char* ps;ps = (char*)malloc(iByte);if (NULL == ps) return false;WideCharToMultiByte(CP_OEMCP, 0, pws, -1, ps, iByte, NULL, NULL);s = std::string(ps);free(ps);return true;
}bool s2ws(const std::string& s, std::wstring& ws)
{const char* ps = s.c_str();int iByte = ::MultiByteToWideChar(CP_OEMCP, 0, ps, -1, NULL, 0);if (iByte == 0) return false;wchar_t* pws;pws = (wchar_t*)malloc(iByte * sizeof(wchar_t));if (NULL == pws) return false;::MultiByteToWideChar(CP_OEMCP, 0, ps, -1, pws, iByte);ws = std::wstring(pws);free(pws);return true;
}
这篇关于wstring_convert的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!