Home >Backend Development >C++ >How to Convert C Strings to Wstrings?

How to Convert C Strings to Wstrings?

Linda Hamilton
Linda HamiltonOriginal
2024-12-29 13:35:141001browse

How to Convert C   Strings to Wstrings?

Converting a C String to a Wstring

In C , converting a string (or char) to a wstring (or wchar_t) allows you to work with wide characters, which are used to represent non-ASCII characters like Japanese Kanji or Cyrillic characters.

Using the Standard Library

For conversions between UTF-8 and UTF-16, the standard library provides a comprehensive solution:

#include <locale>
#include <codecvt>
#include <string>

std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wstr = converter.from_bytes("おはよう");

Example

The following example demonstrates this conversion:

#include <iostream>

int main() {
  std::string a = "Привет всем!";
  std::wstring b = std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>().from_bytes(a);

  std::cout << b << std::endl;
  return 0;
}

Output:

Привет всем!

Legacy Approach (Deprecated)

Note that the codecvt header is deprecated in C 17. For systems with no replacement library, you can use the legacy approach:

#include <wchar.h>

wchar_t* wcs = (wchar_t*)MultiByteToWideChar(CP_UTF8, 0, a.c_str(), -1, NULL, 0);

However, this method may not handle certain Unicode characters correctly.

The above is the detailed content of How to Convert C Strings to Wstrings?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn