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

标签 c++ mfc c-strings stdstring

CString 非常方便,而 std::string 更兼容 STL 容器。我正在使用 hash_map。但是, hash_map 不支持 CString 作为键,所以我想将 CString 转换为 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 以及反之亦然?

最佳答案

根据CodeGuru :

CStringstd::string:

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

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

由于 std::string 只能从 LPSTR/LPCSTR 构造,使用 VC++ 7.x 或更高版本的程序员可以利用转换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::string to CString : (来自 Visual Studio's CString FAQs... )

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

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

换句话说,char-specialization (of CStringT) 即 CStringA, wchar_t-specilization CStringW,和 TCHAR-specialization CString 可以从 char 或宽字符构造,空终止(空终止在这里非常重要) 字符串来源。
阿尔托格 IInspectable修改“空终止”部分 in the comments :

NUL-termination is not required.
CStringT has conversion constructors that take an explicit length argument. This also means that you can construct CStringT objects from std::string objects with embedded NUL characters.

关于c++ - 你如何将 CString 和 std::string std::wstring 相互转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/258050/

相关文章:

c++ - 检测循环依赖的依赖排序

c++ - c++动态改变数组名

C++ rand() 不断返回相同的数字

c++ - 将位图缩小到所需尺寸

C++ ListControl - 图标位置

C 检查重复的字符串条目

c++ - 函数不是全局命名空间的成员

c++ - 如何杀死 MFC 向导按钮的焦点

python - 如何像 python 中的字符串一样索引 C 中的字符串?

c++ - 声明一个没有 const 的 C 风格的字符串是不是很糟糕?如果是这样,为什么?