B
B
Bogdan Karpov2018-04-14 10:07:00
C++ / C#
Bogdan Karpov, 2018-04-14 10:07:00

How to correctly convert wchar_t type to string?

I am writing applications on Visual Studio 2017 (console) in which I need to convert the wchar_t type to string, I came to such a solution, here is part of the code:

WCHAR buffer[2048];
int main()
{
  setlocale(LC_ALL, "Rus");
  string path;
  GetModuleFileName(NULL, buffer, sizeof(buffer) / sizeof(buffer[0]));
  for (int i = 0; i < (sizeof(buffer) / sizeof(buffer[0])); i++) {
    path += buffer[i];
  }

Everything seems to be normal, but the Cyrillic alphabet was not converted instead of Russian letters, some kind of rubbish, how to correctly convert it to the string type?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Shatunov, 2018-04-14
@phpkoder

The type WCHARdepends on the project settings and can be either an alias charor a wchar_t. Widespread use of this type throughout the project is not recommended. introduces uncertainty everywhere.
To store Unicode strings (you have 2017 studio and c++17 by default), there have long been several types of strings at once : std::wstring, std::u16stringand std::u32string.
The type std::wstringstores characters of type wchar_t, which, depending on compiler settings, can take 2 or 4 bytes. This makes the type std::wstringas ambiguous as WCHAR. Therefore, types with a strict character size were created: std::u16stringand std::u32string. Now it is recommended to use them together with std::string.
Your question itself is not about type conversion, because this is easily done with a std::transformlambda, but in converting a single-byte (std::string) encoding to Unicode and vice versa.
For this, the standard library also already has everything you need .

Code example
template< typename TCharType, typename TCharTraits, typename TStringAllocator >
inline void Convert( const std::string& source_string, std::basic_string<TCharType, TCharTraits, TStringAllocator>& dest_string )
{
  std::wstring_convert<std::codecvt_utf8_utf16<TCharType>, TCharType> converter;
  dest_string = converter.from_bytes( source_string );
}

template< typename TCharType, typename TCharTraits, typename TStringAllocator >
inline void Convert( const std::basic_string<TCharType, TCharTraits, TStringAllocator>& source_string, std::string& dest_string )
{
  std::wstring_convert<std::codecvt_utf8_utf16<TCharType>, TCharType> converter;
  dest_string = converter.to_bytes( source_string );
}

And in addition to the standard library, everything you need is also in WinAPI and in the C Run-Time Library .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question