[英]convert std::wstring to const *char in c++
如何在 C++ 中将std::wstring
转换为const *char
?
You can convert a std::wstring
to a const wchar_t *
using the c_str
member function :您可以使用
c_str
成员函数将std::wstring
转换为const wchar_t *
:
std::wstring wStr;
const wchar_t *str = wStr.c_str();
However, a conversion to a const char *
isn't natural : it requires an additional call to std::wcstombs
, like for example:但是,转换为
const char *
并不自然:它需要额外调用std::wcstombs
,例如:
#include <cstdlib>
// ...
std::wstring wStr;
const wchar_t *input = wStr.c_str();
// Count required buffer size (plus one for null-terminator).
size_t size = (wcslen(input) + 1) * sizeof(wchar_t);
char *buffer = new char[size];
#ifdef __STDC_LIB_EXT1__
// wcstombs_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined
size_t convertedSize;
std::wcstombs_s(&convertedSize, buffer, size, input, size);
#else
std::wcstombs(buffer, input, size);
#endif
/* Use the string stored in "buffer" variable */
// Free allocated memory:
delete buffer;
You cannot do this just like that.你不能就那样做。
std::wstring
represents a string of wide (Unicode) characters, while char*
in this case is a string of ASCII characters. std::wstring
表示一串宽 (Unicode) 字符,而char*
在这种情况下是一串 ASCII 字符。 There has to be a code page conversion from Unicode to ASCII.必须有一个从 Unicode 到 ASCII 的代码页转换。
To make the conversion you can use standard library functions such as wcstombs
, or Windows' WideCharToMultiByte
function.要进行转换,您可以使用标准库函数,例如
wcstombs
或 Windows 的WideCharToMultiByte
函数。
Updated to incorporate information from comments, thanks for pointing that out.更新以合并评论中的信息,感谢您指出这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.