How to convert std:string to CString in unicode project(如何在 unicode 项目中将 std:string 转换为 CString)
问题描述
我有一个 std::string
.我需要将此 std:string
转换为 Cstring
.
I have a std::string
.
I need to convert this std:string
to a Cstring
.
我尝试使用 .c_str()
但它仅适用于非 unicode 项目,我使用 unicode 项目(因为非 unicode 项目已被 VS2013 弃用).
I try to use the .c_str()
but it's only for non-unicode project and i use unicode project ( because non unicode project are depreceated wiht VS2013).
任何人都可以告诉我如何在 unicode 项目中将 std::string
转换为 CString
吗?
Anyone could show my how to convert an std::string
to a CString
in unicode project ?
推荐答案
CString
有一个转换构造函数采用 const char*
(CStringT::CStringT
).将 std::string
转换为 CString
非常简单:
CString
has a conversion constructor taking a const char*
(CStringT::CStringT
). Converting a std::string
to a CString
is as simple as:
std::string stdstr("foo");
CString cstr(stdstr.c_str());
这适用于 UNICODE 和 MBCS 项目.如果您的 std::string
包含嵌入的 NUL
字符,则必须使用带有长度参数的转换构造函数:
This works for both UNICODE and MBCS projects. If your std::string
contains embedded NUL
characters you have to use a conversion constructor with a length argument:
std::string stdstr("foo");
stdstr += ' ';
stdstr += "bar";
CString cstr(stdstr.c_str(), stdstr.length());
请注意,转换构造函数隐式使用当前线程的 ANSI 代码页 (CP_THREAD_ACP
) 在 ANSI 和 UTF-16 编码之间进行转换.如果您不能(或不想)更改线程的 ANSI 代码页,但仍需要指定用于转换的显式代码页,则必须使用其他解决方案(例如 ATL 和 MFC 字符串转换宏).
Note that the conversion constructors implicitly use the ANSI code page of the current thread (CP_THREAD_ACP
) to convert between ANSI and UTF-16 encoding. If you cannot (or do not want to) change the thread's ANSI code page, but still need to specify an explicit code page to use for the conversion, you have to use another solution (e.g. the ATL and MFC String Conversion Macros).
这篇关于如何在 unicode 项目中将 std:string 转换为 CString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 unicode 项目中将 std:string 转换为 CString


基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01