How to convert wstring to wchar_t*? C++
Asked Answered
S

4

7

I would like to convert wstring to wchar_t*. I have tried everything what i know, please help. I would like to convert wstring to wchar_t*.

Singularity answered 8/7, 2017 at 11:2 Comment(1)
According to the manual you can obtaine a pointer like this: std::wstring::c_strVizierate
J
7

Did you try reading the reference

const wchar_t* wcs = s.c_str();
Jealousy answered 8/7, 2017 at 11:5 Comment(1)
The OP apparently wants a wchar_t*, not a wchar_t const*, as illustrated in this answer. Starting with C++17, wstring::data() provides that.Sarge
Q
3

There is no way to convert wstring to wchar_t* but you can convert it to const wchar_t* which is what answer by K.Kirsz says.

This is by design because you can access a const pointer but you shouldn't manipulate the pointer. See a related question and its answers.

The best bet is to create a new string using _wcsdup and access the non const buffer, an ascii example is given there.

For unicode:

    wstring str = L"I am a unicode string";
    wchar_t* ptr = _wcsdup(str.c_str());
    // use ptr here....
    free(ptr); // free memory when done
Quisling answered 29/10, 2019 at 15:42 Comment(0)
S
1

I just had this same question and arrived here. Posting my answer a few years later, but this works:

std::wstring wname1 = L"wide string";
wchar_t wname2[1024];
wcscpy(wname2, wname1.c_str());
wchar_t* pfoo = new wchar_t[1024];
wcscpy(pfoo, wname1.c_str());
Schist answered 26/5, 2022 at 18:40 Comment(0)
C
0

Even before C++17, this is possible, just the same way as you can get the mutable char* from a regular std::string – by taking the address of its first element:

std::wstring s = ...;
wchar_t* str_ptr = &s[0]
Corruptible answered 21/9 at 9:11 Comment(1)
@MichaelChourdakis It didn't originally (C++03), but as of C++11 it is now guaranteed. See for example stackoverflow.com/a/11752722Corruptible

© 2022 - 2024 — McMap. All rights reserved.