Home  >  Article  >  Backend Development  >  Why are wchar_t strings printed as hex values instead of characters when using cout?

Why are wchar_t strings printed as hex values instead of characters when using cout?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-16 15:43:03116browse

Why are wchar_t strings printed as hex values instead of characters when using cout?

Printing wchar_t Values to Console

In your code, you attempted to print wchar_t strings (wide character strings) using the standard output stream (cout). However, this results in hex values being printed instead of the actual characters. To print wchar_t strings correctly, you need to use the wide character output stream (wcout) instead.

Consider the example you provided:

#include <iostream>

using namespace std;

int main() {
    wchar_t en[] = L"Hello";
    wchar_t ru[] = L"Привет"; // Russian language
    cout << ru << endl << en; // Prints hex values
    return 0;
}

To print the wchar_t strings correctly, replace cout with wcout:

...
    wcout << ru << endl << en; // Prints actual characters
...

With this change, the program will output the Russian characters "Привет" and "Hello" as expected. Note that the default locale may not support all characters in the wchar_t string, so some characters may not be displayed correctly.

The above is the detailed content of Why are wchar_t strings printed as hex values instead of characters when using cout?. 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