[TOC]

string <–> CString

string -> CString

1
2
3
4
5
std::string str = "string";
CString csRet;
// csRet.Format("%s", str.c_str());
// 如果上句报错就使用
csRet.Format(_T("%s"), str.c_str());

CString -> string

1
2
3
CString cstr("string");

string

string < – > wstring

string -> wstring

solution 1:

1
2
3
4
5
6
7
8
9
10
#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);
}

solution 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
wstring stringToWstring(std::string str)
{
wstring result = L"";
int nLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);

if (nLen == 0)
return result;

TCHAR* buffer = new TCHAR[nLen + 1];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, nLen);

buffer[nLen] = '\0';
result.append(buffer);

delete[] buffer;
return result;
}

wstring -> string

1
2
3
4
5
6
//convert wstring to string 
inline std::string to_byte_string(const std::wstring& input)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
return converter.to_bytes(input);
}

DWORD <—> string

1
2
3
4
5
string DwordToString(DWORD val)
{
string cur_str = to_string(long long (val));
return cur_str;
}
1
2
3
4
5
6
DWORD StringToDword(string val)
{
DWORD cur_dword;
sscanf(val.c_str(),"%ul",&cur_dword);
return cur_dword;
}

更多查看已实现的编码转换文件:

win_str_utils

win_str_utils.md