gpt4 book ai didi

c++ - 将 std::wstring 转换为 WCHAR*

转载 作者:IT老高 更新时间:2023-10-28 21:54:19 31 4
gpt4 key购买 nike

我不知道如何将 std::wstring 转换为 WCHAR*

std::wstring wstrProcToSearch;
WCHAR * wpProcToSearch = NULL;

std::wcin >> wstrProcToSearch; // input std::wstring
// now i need to convert the wstring to a WCHAR*

有谁知道如何做到这一点?

最佳答案

如果您想从 std::wstring 转换为 const WCHAR*(即返回的指针提供 只读访问权限字符串内容),然后调用 std::wstring::c_str() 方法就可以了:

std::wstring wstrProcToSearch;
std::wcin >> wstrProcToSearch; // input std::wstring

// Convert to const WCHAR* (read-only access)
const WCHAR * wpszProcToSearch = wstrProcToSearch.c_str();

相反,如果你想修改 std::wstring 的内容,情况就不同了。您可以使用 &wstr[0](其中 wstrstd::wstring 的非空实例)来访问 std::wstring(从第一个字符的地址开始,注意字符在内存中是连续存储的),但是一定要注意不要超出string的预分配内存。

一般来说,如果你有一个长度为 Lstd::wstring,你可以从索引 0 访问字符到 (L-1).

之前 C++17, overwriting the terminating '\0' (位于索引 L)是未定义的行为(实际上,它在 Visual C++ 上是可以的,至少在 VC9/VS2008 和 VC10/VS2010 中是这样)。

从 C++17 开始,用另一个 NUL 覆盖终止 NUL ('\0') valid并且不再是未定义的行为。

如果字符串的大小不合适(即它不足以满足您的需要),那么您可以调用 std::wstring::resize() 为新字符腾出空间(即调整内部 std::wstring 的缓冲区),然后使用 &wstr[0] 来读写 std::wstring 的内容.

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

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com