Joshua Son
Joshua Son

Reputation: 1897

How do I convert wchar_t* to string?

I am new to C++.

And I am trying to convert wchar_t* to string.

I cannot use wstring in condition.

I have code below:

wchar_t *wide   = L"中文";
wstring ret     = wstring( wide );
string str2( ret.begin(), ret.end() );

But str2 returns some strange characters.

Where do I have to fix it?

Upvotes: 3

Views: 8245

Answers (2)

nim
nim

Reputation: 382

I'm not sure what platform you're targeting. If you're on Windows platform you can call WideCharToMultiByte API function. Refer to MSDN for documentation.

If you're on Linux, I think you can use libiconv functions, try google.

Of course there is a port of libiconv for Windows.

In general this is a quite complex topic for a new beginners if you know nothing about character encodings - there are a lot of background knowledge to have to learn.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

You're trying to do it backwards. Instead of truncating wide characters to chars (which is very lossy), expand your chars to wide characters.

That is, transform your std::string into an std::wstring and concatenate the two std::wstrings.

Upvotes: 3

Related Questions