5

I have smalll problem i want to convert unicode into Multi byte is there any way

subbu
  • 3,229
  • 13
  • 49
  • 70
  • 3
    Did you check wcstombs? http://www.cplusplus.com/reference/clibrary/cstdlib/wcstombs/ – vpram86 Oct 06 '09 at 13:12
  • I think you will need to give us some more details. What unicode format do you have now and which multibyte encoding do you want to use? – Rik Heywood Oct 06 '09 at 13:12

6 Answers6

7
std::string NarrowString(const std::wstring& str, const char* localeName = "C")
{
  std::string result;
  result.resize(str.size());

  std::locale loc(localeName);

  std::use_facet<std::ctype<wchar_t> >(loc).narrow(
    str.c_str(), str.c_str() + str.size(), '?',  &*result.begin());

  return result;
}

It should use the current locale to convert the unicode string. For the caracters that do not belong in the codepage the '?' caracter is being used. Tested with Visual C++ 2005/2008.

Cristian Adam
  • 4,749
  • 22
  • 19
  • Good, but how to detect if it was successfully converted or an '?' was used for a character? Round trip conversion?? – Narek Nov 20 '12 at 07:55
5

Three options offhand:

ctacke
  • 66,480
  • 18
  • 94
  • 155
3

wcstombs works beautifully for me :)

Goz
  • 61,365
  • 24
  • 124
  • 204
1

In most cases WideCharToMultiByte() will be enough.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
0

There's WideCharToMultiByte winapi function.

Paulius
  • 5,790
  • 7
  • 42
  • 47
0

use WideCharToMultiByte

Ahmed
  • 7,148
  • 12
  • 57
  • 96