C++11:string和wstring之间互转换

# C++

C++11:string和wstring之间互转换

今天打算做string到wstring转换时从哪里找来的,贴出代码,以防再忘记。C++11后UTF8编码转换还真是方便

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <string>
#include <locale>
#include <codecvt>

// convert string to wstring
inline std::wstring to_wide_string(const std::string& input)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
return converter.from_bytes(input);
}
// convert wstring to string
inline std::string to_byte_string(const std::wstring& input)
{
//std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
return converter.to_bytes(input);
}