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

标签 c++

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

最佳答案

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

std::wstring wStr;
const wchar_t *str = wStr.c_str();

然而,转换成 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;

关于c++ - 在 C++ 中将 std::wstring 转换为 const *char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4387288/

相关文章:

C++ 为什么我的文本数组在我用另一个覆盖它后不会改变?

c++ - 检测继承类并将其转换为基类

c++ - 从围绕 xyz 的旋转找到 xyz 方向

c++ - 从 wxWidgets 和 C++ 开始

c++ - 为什么 C++ 编译器不做更好的常量折叠?

c++ - C++ SFML Gamedev书-ResourceHolder类中的未解析外部符号

c++ - 将 yyin 设置为 "emulated"文件*?

C++:为指向两种类型之一的指针保留打开选项

c++ - For循环不执行

c++ - 关于在 C++ 代码中使用 realloc 实现的问题