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
L
indicates 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
wc
is declared as a wide character and initialized with the literalL'Ω'
, whereL
indicates a wide character literal. - The
wcout
stream 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
wstr
is declared as a wide character string literal using theL
prefix. - The
wcout
stream 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_t
is used for wide characters and supports larger character sets like Unicode.- The size of
wchar_t
is platform-dependent and may vary. - Use
wcout
for printing wide characters and strings. - Wide character literals and strings must be prefixed with
L
.