c++stlwchar

Why can't wcout use the hex keyword to output hexadecimal format?


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

Solution

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

    wcout << hex << (unsigned)ch;