3

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?

Joshua Son
  • 1,839
  • 6
  • 31
  • 51

2 Answers2

3

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

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.

nim
  • 384
  • 2
  • 14