如何在 unicode 项目中将 std:string 转换为 CString
How to convert std:string to CString in unicode project
我有一个std::string
.我需要将此std:string
转换为Cstring
.
我尝试使用.c_str()
但它仅适用于非 unicode 项目,并且我使用 unicode 项目(因为 VS2013 已弃用非 unicode 项目)。
任何人都可以向我展示如何在 unicode 项目中将std::string
转换为CString
?
CString
有一个采用const char*
(CStringT::CStringT
)的转换构造函数。将std::string
转换为CString
非常简单:
std::string stdstr("foo");
CString cstr(stdstr.c_str());
这适用于UNICODE和MBCS项目。如果std::string
包含嵌入的NUL
字符,则必须使用带有长度参数的转换构造函数:
std::string stdstr("foo");
stdstr += ' ';
stdstr += "bar";
CString cstr(stdstr.c_str(), stdstr.length());
请注意,转换构造函数隐式使用当前线程的 ANSI 代码页 ( CP_THREAD_ACP
) 在 ANSI 和 UTF-16 编码之间进行转换。如果不能(或不想)更改线程的 ANSI 代码页,但仍需要指定用于转换的显式代码页,则必须使用其他解决方案(例如 ATL 和 MFC 字符串转换宏)。
Unicode CString
的构造函数接受char*
,所以你可以这样做:
std::string str = "string";
CString ss(str.c_str());
使用 ATL 转换宏。当您使用 CString 时,它们在任何情况下都有效。CString 要么是 MBCS 要么是 Unicode...取决于您的编译器设置。
std::string str = "string";
CString ss(CA2T(str.c_str());
奖励:如果您经常使用转换,您可以定义一个宏:
#define STDTOCSTRING(s) CString(s.c_str())
因此,您的代码更具可读性。
相关文章:
- 使用char类型将decimal转换为string,将string转换为decimal
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 如何将带有十六进制值的 std::string 转换为 std::vector<无符号字符>
- 无法从'const std::string [3]'转换为'std::string'
- 从 std::string 转换为 const 无符号整数
- C++ 模板函数无法将"std:string"转换为"double"作为回报
- 将 std::string 转换为 const char* 用于 printf 消耗
- 将 std::string 转换为 const tchar*
- 如何在PHPCPP库中将C++map<string,map<string>>转换为php::value?
- 将 std::string 转换为具有特殊字符的 FString (TCHAR / wstring)
- 将 std::string 转换为 wchar_t* 的类型定义
- 在 C++03 中将 std::string 转换为 int
- 将 'hana::string' 转换为 'constexpr const char (&)[]'
- 正确的交叉平台从 std::string 转换为 'const TCHAR *'
- 从矢量<string>转换为wchar_t**
- 将 std::vector<std::string> 转换为 const char* const*
- 将 std::string 转换为 boost::asio::streambuf
- C++ SNAP 库将 std::string 转换为 TStr
- 自动将 std::string 转换为 char* 而无需每次都调用 c_str() 的最佳方法
- 将 std::string 转换为 Swift String