我想将std :: string转换为const wchar_t *

问题描述 投票:52回答:4

有什么方法吗?我的电脑是AMD64。

::std::string str;
BOOL loadU(const wchar_t* lpszPathName, int flag = 0);

我用的时候:

loadU(&str);

VS2005编译器说:

Error 7 error C2664:: cannot convert parameter 1 from 'std::string *__w64 ' to 'const wchar_t *'

我该怎么做?

c++ stl wchar-t stdstring
4个回答
40
投票

如果你有一个std :: wstring对象,你可以在它上面调用c_str()来获得一个wchar_t*

std::wstring name( L"Steve Nash" );
const wchar_t* szName = name.c_str();

但是,由于您在窄字符串上操作,因此首先需要加宽它。这里有各种选择;一种是使用Windows内置的MultiByteToWideChar例程。这将给你一个LPWSTR,相当于wchar_t*


86
投票

首先将其转换为std :: wstring:

std::wstring widestr = std::wstring(str.begin(), str.end());

然后得到C字符串:

const wchar_t* widecstr = widestr.c_str();

这仅适用于ASCII字符串,但如果基础字符串是UTF-8编码则不起作用。使用MultiByteToWideChar()之类的转换例程可确保正确处理此方案。


9
投票

您可以使用ATL文本转换宏将narrow(char)字符串转换为wide(wchar_t)字符串。例如,要转换std :: string:

#include <atlconv.h>
...
std::string str = "Hello, world!";
CA2W pszWide(str.c_str());
loadU(pszWide);

您还可以指定代码页,因此如果您的std :: string包含UTF-8字符,您可以使用:

CA2W pszWide(str.c_str(), CP_UTF8);

非常有用,但仅限Windows。


4
投票

如果您在Linux / Unix上,请查看GNU C中定义的mbstowcs()和wcstombs()(来自ISO C 90)。

  • mbs代表“Multi Bytes String”,基本上是通常的零终止C字符串。
  • wcs代表Wide Char String,是一个wchar_t数组。

有关宽字符的更多背景详细信息,请查看glibc文档here

© www.soinside.com 2019 - 2024. All rights reserved.