C++ 如何将 wchar_t* 转换为 std::string?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4339960/
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-28 15:09:50  来源:igfitidea点击:

How do I convert wchar_t* to std::string?

c++stringstdstringwchar-t

提问by codefrog

I changed my class to use std::string (based on the answer I got herebut a function I have returns wchar_t *. How do I convert it to std::string?

我将我的班级更改为使用 std::string (基于我在这里得到的答案但我有一个函数返回 wchar_t *。如何将其转换为 std::string?

I tried this:

我试过这个:

std::string test = args.OptionArg();

but it says error C2440: 'initializing' : cannot convert from 'wchar_t *' to 'std::basic_string<_Elem,_Traits,_Ax>'

但它说错误 C2440: 'initializing' : cannot convert from 'wchar_t *' to 'std::basic_string<_Elem,_Traits,_Ax>'

采纳答案by Steve Townsend

You could just use wstringand keep everything in Unicode

您可以使用wstring并保留 Unicode 中的所有内容

回答by Ulterior

std::wstring ws( args.OptionArg() );
std::string test( ws.begin(), ws.end() );

回答by Praetorian

You can convert a wide char string to an ASCII string using the following function:

您可以使用以下函数将宽字符字符串转换为 ASCII 字符串:

#include <locale>
#include <sstream>
#include <string>

std::string ToNarrow( const wchar_t *s, char dfault = '?', 
                      const std::locale& loc = std::locale() )
{
  std::ostringstream stm;

  while( *s != L'
typedef std::basic_string<char> string
' ) { stm << std::use_facet< std::ctype<wchar_t> >( loc ).narrow( *s++, dfault ); } return stm.str(); }

Be aware that this will just replace any wide character for which an equivalent ASCII character doesn't exist with the dfaultparameter; it doesn't convert from UTF-16 to UTF-8. If you want to convert to UTF-8 use a library such as ICU.

请注意,这只会替换dfault参数中不存在等效 ASCII 字符的任何宽字符;它不会从 UTF-16 转换为 UTF-8。如果要转换为 UTF-8,请使用诸如ICU 之类的库。

回答by paulluap

This is an old question, but if it's the case you're not really seeking conversions but rather using the TCHAR stuff from Mircosoft to be able to build both ASCII and Unicode, you could recall that std::string is really

这是一个老问题,但如果是这种情况,您并不是真正在寻求转换,而是使用 Mircosoft 的 TCHAR 内容来构建 ASCII 和 Unicode,那么您可能还记得 std::string 确实是

#include <string>
namespace magic {
typedef std::basic_string<TCHAR> string;
}

So we could define our own typedef, say

所以我们可以定义我们自己的 typedef,比如

const wchar_t* val = L"hello mfc";
std::string test((LPCTSTR)CString(val));

Then you could use magic::stringwith TCHAR, LPCTSTR, and so forth

然后你可以使用magic::stringwith TCHAR, LPCTSTR, 等等

回答by Danil

just for fun :-):

只是为了好玩 :-):

wchar_t wstr[500];
char string[500];
sprintf(string,"%ls",wstr);

回答by Pamela Hauff

Following code is more concise:

下面的代码更简洁:

##代码##