将std :: wstring转换为WCHAR * [英] Convert std::wstring to WCHAR*
问题描述
我不知道如何将 std :: wstring
转换为 WCHAR *
I have no idea how to convert a std::wstring
to a 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()
方法就可以了:
If you want to convert from std::wstring
to const WCHAR*
(i.e. the returned pointer gives read-only access to the string content), then calling std::wstring::c_str()
method is just fine:
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]
(其中 wstr
是 std :: wstring
)以访问 std :: wstring
的内容(从其第一个字符的地址开始,并注意该字符连续存储在内存中),但您必须注意不要溢出字符串的预分配内存。
Instead, if you want to modify std::wstring
's content, things are different. You can use &wstr[0]
(where wstr
is a non-empty instance of std::wstring
) to access the content of the std::wstring
(starting from the address of its first characters, and noting that characters are stored contiguously in memory), but you must pay attention to not overrun string's pre-allocated memory.
通常,如果您有 std :: wstring
长度为 L
,则可以访问索引 0
$ b $中的字符b到(L-1)
。
覆盖终止的'\0'
(位于索引 L
)是未定义的行为(实际上,在Visual C ++上是可以的,至少在VC9 / VS2008和VC10 / VS2010中是可以的)。
In general, if you have a std::wstring
of length L
, you can access characters from index 0
to (L-1)
.
Overwriting the terminating '\0'
(located at index L
) is undefined behavior (in practice, it's OK on Visual C++, at least with VC9/VS2008 and VC10/VS2010).
如果字符串的大小不合适(即,它的大小不足以满足您的需要),则可以调用 std :: wstring :: resize()
到m为新角色留出空间(即调整内部 std :: wstring
的缓冲区的大小),然后使用& wstr [0]
进行读写 std :: wstring
的内容。
If the string has not the proper size (i.e. it's not big enough for your needs), then you can call std::wstring::resize()
to make room for new characters (i.e. resizing internal std::wstring
's buffer), and then use &wstr[0]
to read-write std::wstring
's content.
这篇关于将std :: wstring转换为WCHAR *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!