在 C++ 中将 std::wstring 转换为 const *char

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

convert std::wstring to const *char in c++

c++

提问by subs

How can I convert std::wstringto const *charin C++?

如何在 C++ 中转换std::wstringconst *char

采纳答案by icecrime

You can convert a std::wstringto a const wchar_t *using the c_strmember function :

您可以使用成员函数将 a 转换std::wstring为 a :const wchar_t *c_str

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:

但是,转换为 aconst 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;

回答by Jon

You cannot do this just like that. std::wstringrepresents a string of wide (Unicode) characters, while char*in this case is a string of ASCII characters. There has to be a code page conversion from Unicode to ASCII.

你不能就那样做。std::wstring表示一串宽 (Unicode) 字符,而char*在本例中是一串 ASCII 字符。必须有一个从 Unicode 到 ASCII 的代码页转换。

To make the conversion you can use standard library functions such as wcstombs, or Windows' WideCharToMultiBytefunction.

要进行转换,您可以使用标准库函数,例如wcstombs、 或 Windows 的WideCharToMultiByte函数。

Updatedto incorporate information from comments, thanks for pointing that out.

更新以合并评论中的信息,感谢您指出这一点。