Home > Backend Development > C++ > How to Convert a String (or char) to a wstring (or wchar_t) in C ?

How to Convert a String (or char) to a wstring (or wchar_t) in C ?

Barbara Streisand
Release: 2025-01-04 19:24:39
Original
180 people have browsed it

How to Convert a String (or char) to a wstring (or wchar_t) in C  ?

C Convert string (or char) to wstring (or wchar_t)

Problem:

Given a string or char variable, how can we assign its contents to a wstring or wchar_t variable?

Solution:

Assuming the input string is encoded in UTF-8, the standard library (C 11 and newer) includes several techniques for converting between UTF-8 and UTF-16:

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

using namespace std;

// Create a converter using the UTF-8/UTF-16 codecvt
wstring_convert<codecvt_utf8_utf16<wchar_t>> converter;

// Convert a narrow (UTF-8) string to a wide (UTF-16) string
wstring wide = converter.from_bytes(narrow);

// Convert a wide (UTF-16) string to a narrow (UTF-8) string
string narrow = converter.to_bytes(wide);
Copy after login

Example (Online Compilable and Runnable):

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

int main() {
  // Sample input string in UTF-8 (see notes below for real-world scenarios):
  string s = "おはよう";

  // Create a wstring to store the converted string
  wstring ws;

  // Convert the narrow (UTF-8) string to wide (UTF-16)
  std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> conv;
  ws = conv.from_bytes(s);

  // Print the converted wstring
  wcout << ws << endl;

  return 0;
}
Copy after login

Notes:

  1. Ensure that the input string is indeed encoded in UTF-8. Non-UTF-8 encodings will not produce the correct conversion.
  2. The codecvt_utf8_utf16 converter assumes little-endian byte order for UTF-16. If your system uses big-endian byte order, consider using codecvt_utf8 instead.

    The above is the detailed content of How to Convert a String (or char) to a wstring (or wchar_t) in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template