你如何将 CString 和 std::string std::wstring 相互转换?

新手上路,请多包涵

CString 相当方便,而 std::string 更兼容STL容器。我正在使用 hash_map 。 However, hash_map does not support CString s as keys, so I want to convert the CString into a std::string .

写一个 CString 哈希函数似乎需要很多时间。

 CString -----> std::string

我怎样才能做到这一点?

 std::string -----> CString:

inline CString toCString(std::string const& str)
{
    return CString(str.c_str());
}

我对吗?


编辑:

这里有更多问题:

如何从 wstring 转换为 CString 反之亦然?

 // wstring -> CString
std::wstring src;
CString result(src.c_str());

// CString -> wstring
CString src;
std::wstring des(src.GetString());

这有什么问题吗?

此外,如何从 std::wstring 转换为 std::string 反之亦然?

原文由 user25749 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

根据 CodeGuru

CStringstd::string

 CString cs("Hello");
std::string s((LPCTSTR)cs);

但是: std::string 不能总是从 LPCTSTR 构造。即 UNICODE 构建的代码将失败。

As std::string can construct only from LPSTR / LPCSTR , a programmer who uses VC++ 7.x or better can utilize conversion classes such as CT2CA 作为中介。

 CString cs ("Hello");
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString (cs);
// construct a std::string using the LPCSTR input
std::string strStd (pszConvertedAnsiString);

std::stringCString : (来自 Visual Studio 的 CString FAQs… )

 std::string s("Hello");
CString cs(s.c_str());

CStringT 可以从字符或宽字符串构造。即它可以从 char* (即 LPSTR )或 wchar_t*LPWSTR )转换

In other words, char-specialization (of CStringT ) ie CStringA , wchar_t -specilization CStringW , and TCHAR –specialization --- CString 可以从 char 或宽字符构造,空终止(空终止在这里非常重要)字符串来源。

Althoug IInspectable 修改了 评论中 的“null-termination”部分:

不需要 NUL 终止

CStringT 具有采用显式长度参数的转换构造函数。这也意味着您可以从 std::string 嵌入了 NUL 字符的对象构造 CStringT 对象。

原文由 VonC 发布,翻译遵循 CC BY-SA 3.0 许可协议

CString 有方法 GetString() ,如果您使用的是 Unicode,则返回 LPCWSTR 类型,否则返回 LPCSTR

在 Unicode 情况下,您必须通过 wstring 传递它:

 CString cs("Hello");
wstring ws = wstring(cs.GetString());
string s = string(ws.begin(), ws.end());

否则,您可以直接转换字符串:

 CString cs("Hello");
string s = string(cs.GetString());

原文由 GiaMat45 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题