AP.
AP.

Reputation: 5323

assign a LPWSTR to an existing wstring

I am looking for a way to copy the content of a LPWSTR to an existing wstring. I've found a lot of examples to do the reverse but I am still looking for a way to do it.

Thanks

Upvotes: 1

Views: 5995

Answers (4)

tenfour
tenfour

Reputation: 36896

You cannot guarantee that .c_str() will render the same pointer after modifying the string, period (if that's what you're trying to do).

The correct way to assign a LPWSTR to a std::wstring object is to use operator=(), like:

std::wstring existingString = L"text";
LPCWSTR c_str = L"more text";
existingString = c_str;

But this is extremely simple; maybe you should elaborate on what you're trying to do if this doesn't cover it.

Upvotes: 1

Indy9000
Indy9000

Reputation: 8871

Why not

LPWSTR k = L"my string";
std::wstring ws(k);

or if you really have to assign to an existing wstring

 std::wstring existing;
 ....
 existing.assign(k);

Upvotes: 1

Johann Gerell
Johann Gerell

Reputation: 25591

Doing that is a hack and implementation dependent. The correct way is to assign the LPCWSTR to the wstring - the compiler will then make sure that the contents are correctly copied into the existing char buffer if it exists or first allocate it and then copy.

Upvotes: 1

WhozCraig
WhozCraig

Reputation: 66234

If this is to save the allocation time, the std::wstring is good to do the right thing usually, but if you really absolutely must do this...

wcsncpy(&wstr[0], wsrc, wstr.size()-1);
wstr[wstr.size()-1] = 0;

I felt really dirty writing that. Note: this will NOT allocate space in the wstr objet. further, i guarantee it will blow up if wstr, in fact, is currently empty, so beware. it will only use whatever you already have there for storage. If you want/need more space then .resize() appropriately, but as I said before, the assignment operator for std::wstring will really do what you want if you just let it.

Upvotes: 1

Related Questions