[TOC]
string <—> CString
string -> CString
cpp
std::string str = "string";
CString csRet;
// csRet.Format("%s", str.c_str());
// 如果上句报错就使用
csRet.Format(_T("%s"), str.c_str());CString -> string
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*
cpp
std::string str = "hello";
const char* p = str.c_str(); // 只读,不保证以 '\0' 结尾(C++11 起保证)
const char* d = str.data(); // 同 c_strchar* -> string
cpp
const char* p = "hello";
std::string str(p); // 以 '\0' 结尾的 C 字符串
std::string str2(p, len); // 指定长度(可含 '\0')wstring < — > CString
wstring -> CString
cpp
std::wstring ws = L"宽字符串";
CString cstr(ws.c_str()); // CStringW 可直接用 wchar_t* 构造CString -> wstring
cpp
CString cstr(_T("宽字符串"));
std::wstring ws(cstr.GetString()); // Unicode 工程下直接转换string < — > wstring
string -> wstring
solution 1:
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:
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
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
cpp
string DwordToString(DWORD val)
{
string cur_str = to_string(long long (val));
return cur_str;
}cpp
DWORD StringToDword(string val)
{
DWORD cur_dword;
sscanf(val.c_str(),"%ul",&cur_dword);
return cur_dword;
}更多查看已实现的编码转换文件: