C++ 如何在 unicode 项目中将 std:string 转换为 CString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19616828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:00:19  来源:igfitidea点击:

How to convert std:string to CString in unicode project

c++stringvisual-studiomfc

提问by Walter Fabio Simoni

I have a std::string. I need to convert this std:stringto a Cstring.

我有一个std::string. 我需要将其转换std:stringCstring.

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).

我尝试使用.c_str()但它仅用于非 unicode 项目,我使用 unicode 项目(因为非 unicode 项目已被 VS2013 弃用)。

Anyone could show my how to convert an std::stringto a CStringin unicode project ?

任何人都可以向我展示如何将 an 转换std::stringCStringunicode 项目?

回答by IInspectable

CStringhas a conversion constructor taking a const char*(CStringT::CStringT). Converting a std::stringto a CStringis as simple as:

CString有一个采用const char*( CStringT::CStringT)的转换构造函数。将 a 转换std::string为 aCString非常简单:

std::string stdstr("foo");
CString cstr(stdstr.c_str());

This works for both UNICODE and MBCS projects. If your std::stringcontains embedded NULcharacters you have to use a conversion constructor with a length argument:

这适用于 UNICODE 和 MBCS 项目。如果您std::string包含嵌入NUL字符,则必须使用带有长度参数的转换构造函数:

std::string stdstr("foo");
stdstr += '
std::string str = "string";
CString ss(CA2T(str.c_str());
'; stdstr += "bar"; CString cstr(stdstr.c_str(), stdstr.length());

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).

请注意,转换构造函数隐式使用当前线程 ( CP_THREAD_ACP)的 ANSI 代码页在 ANSI 和 UTF-16 编码之间进行转换。如果您不能(或不想)更改线程的 ANSI 代码页,但仍需要指定用于转换的显式代码页,则必须使用另一种解决方案(例如ATL 和 MFC 字符串转换宏)。

回答by xMRi

Use the ATL conversion macros. They work in every case, when you use CString. CString is either MBCS or Unicode... depends on your Compiler Settingss.

使用 ATL 转换宏。当您使用 CString 时,它们适用于所有情况。CString 是 MBCS 或 Unicode...取决于您的编译器设置。

std::string str = "string";
CString ss(str.c_str());

回答by cfanhacker

Unicode CString's constructor accepts char*so you can do this:

UnicodeCString的构造函数接受,char*所以你可以这样做:

#define STDTOCSTRING(s) CString(s.c_str())

回答by iKanor

Bonus: if you use the conversion frequently you can define a macro:

奖励:如果您经常使用转换,您可以定义一个宏:

##代码##

so your code is more readable.

所以你的代码更具可读性。