[TOC]

string <—> CString

string -> CString

C++cpp
std::string str = "string";
CString csRet;
// csRet.Format("%s", str.c_str());
// 如果上句报错就使用
csRet.Format(_T("%s"), str.c_str());

CString -> string

C++cpp
CString cstr("string");
std::string str;
 
#ifdef _UNICODE
// 工程为 Unicode 时,CString 实际是 CStringW,需要宽转窄
int nLen = WideCharToMultiByte(CP_ACP, 0, cstr, cstr.GetLength(), NULL, 0, NULL, NULL);
char* pBuf = new char[nLen + 1];
WideCharToMultiByte(CP_ACP, 0, cstr, cstr.GetLength(), pBuf, nLen, NULL, NULL);
pBuf[nLen] = '\0';
str = pBuf;
delete[] pBuf;
#else
// 工程为 ANSI/MBCS 时,CString 实际是 CStringA,可直接转换
str = cstr.GetBuffer(0);
#endif

简洁写法(Unicode 工程):std::string str = CW2A(cstr);(需包含 <atlconv.h>,或使用 ATL 的 CT2A)。

string < — > char*

string -> const char*

C++cpp
std::string str = "hello";
const char* p = str.c_str();   // 只读,不保证以 '\0' 结尾(C++11 起保证)
const char* d = str.data();    // 同 c_str

char* -> string

C++cpp
const char* p = "hello";
std::string str(p);            // 以 '\0' 结尾的 C 字符串
std::string str2(p, len);      // 指定长度(可含 '\0')

wstring < — > CString

wstring -> CString

C++cpp
std::wstring ws = L"宽字符串";
CString cstr(ws.c_str());   // CStringW 可直接用 wchar_t* 构造

CString -> wstring

C++cpp
CString cstr(_T("宽字符串"));
std::wstring ws(cstr.GetString());   // Unicode 工程下直接转换

string < — > wstring

string -> wstring

solution 1:

C++cpp
#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:

C++cpp
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

C++cpp
//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

C++cpp
string DwordToString(DWORD val)
{
	string cur_str = to_string(long long (val));
	return cur_str;
}
C++cpp
DWORD StringToDword(string val)
{
	DWORD cur_dword;
	sscanf(val.c_str(),"%ul",&cur_dword);
	return cur_dword;
}

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

win_str_utils

win_str_utils.md