0

I have entered a wchar type variable and want to see the hexadecimal of the variable. However,when I use the wcout keyword, I can't always output hexadecimal. Is there a grammatical error?

#include <iostream>

void test_wide_character_input() {
  using namespace std;
  wchar_t ch = L'?';
  wcout << ch << endl;
  wcout << hex;
  wcout << ch << endl;

  cout << "---" << endl;

  wchar_t w_ch = L'1';
  wcout << w_ch << endl;
  cout << w_ch << endl;
  cout << hex;
  cout << w_ch << endl;
}

int main() {
  test_wide_character_input();
  return 0;
}

out:

PS C:\Users\j30022312\Downloads\Relearn_C_Plus_Plus-main\Relearn_C_Plus_Plus-main\PART_2_The_C++_Library\Chapter_8_The_IO_Library\examples> .\a.exe
?
?
---
1
49
31
  • 1
    Try `wcout << (unsigned)ch << endl;`. Hex output applies to integers not characters. When you output a `wchar_t` to `cout` it's an integer, but when you output a `wchar_t` to `wcout` it's a character. – john Nov 16 '22 at 08:58
  • You [should not mix](https://stackoverflow.com/a/22950466/14637) `wcout` and `cout`; on my system I'm getting only part of the output if I try that. – Thomas Nov 16 '22 at 08:59

1 Answers1

1

Change the character to unsigned int type before converting it to hexadecimal like this:

wcout << hex << (unsigned)ch;
YourDoge
  • 41
  • 3