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);
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; }
Notes:
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!