You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何wcout无法使用hex操纵符输出wchar_t变量的十六进制格式?

问题:wcout无法输出wchar_t的十六进制值

我定义了wchar_t类型变量,希望查看该变量的十六进制值,但使用wcout配合hex操纵符时,始终无法输出十六进制格式。请问是否存在语法错误?

相关代码如下:

#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;
}

程序运行输出:

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

原因与解决办法

这不是语法错误,是wcout处理wchar_t的默认行为导致的:

  • wcout输出wchar_t类型时,默认会把它当作宽字符打印,hex操纵符只对整数类型的输出生效,对字符类型无影响。
  • 而cout输出wchar_t时,会自动将其提升为int类型,所以hex能生效并输出对应十六进制值。

要让wcout输出wchar_t的十六进制值,只需把wchar_t强制转换为整数类型即可,推荐用static_cast做类型转换:

修改后的代码示例:

#include <iostream>

void test_wide_character_input() {
  using namespace std;
  wchar_t ch = L'?';
  wcout << ch << endl;
  wcout << hex;
  // 强制转换为无符号整数,确保十六进制输出正确
  wcout << static_cast<unsigned int>(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;
}

修改后运行,wcout就能输出?的十六进制值(如3f)和1的十六进制值(31)了。

内容的提问来源于stack exchange,提问作者yang jiang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:01:06