C++ wchar_t
The wchar_t keyword in C++ is a data type used to represent wide characters. It is designed to store larger character sets, such as Unicode, which cannot be represented by the standard char type.
The size of wchar_t is implementation-dependent but is typically larger than char, allowing it to hold more complex character encodings.
The wchar_t type is useful when working with international character sets or when characters require more than one byte to represent.
Syntax
</>
Copy
wchar_t variable_name = L'character';
- wchar_t
- The keyword used to declare a wide character variable.
- variable_name
- The name of the variable that will store the wide character.
- L’character’
- The prefix
Lindicates a wide character literal.
Examples
Example 1: Declaring and Printing a Wide Character
This example demonstrates how to declare and print a wide character using wchar_t.
</>
Copy
#include <iostream>
#include <cwchar> // For wide character functions
using namespace std;
int main() {
wchar_t wc = L'Ω'; // Greek letter Omega
wcout << L"Wide character: " << wc << endl;
return 0;
}
Output:
Wide character: Ω
Explanation:
- The variable
wcis declared as a wide character and initialized with the literalL'Ω', whereLindicates a wide character literal. - The
wcoutstream is used to print wide characters and strings. - The output displays the wide character
Ω.
Example 2: Wide Character String
This example demonstrates how to declare and print a wide character string.
</>
Copy
#include <iostream>
#include <cwchar> // For wide character functions
using namespace std;
int main() {
const wchar_t* wstr = L"Hello, World! 🌍";
wcout << L"Wide string: " << wstr << endl;
return 0;
}
Output:
Wide string: Hello, World! 🌍
Explanation:
- The variable
wstris declared as a wide character string literal using theLprefix. - The
wcoutstream is used to print wide character strings. - The output displays the wide string, including the emoji
🌍, which requires wide character support.
Key Points about wchar_t
wchar_tis used for wide characters and supports larger character sets like Unicode.- The size of
wchar_tis platform-dependent and may vary. - Use
wcoutfor printing wide characters and strings. - Wide character literals and strings must be prefixed with
L.
