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

C++20中使用char16_t与char32_t在Eclipse 2021显示「猫」的实现方法

原有代码问题分析

你现有测试代码存在的核心问题是:std::cout 没有为 char16_t、char32_t 类型重载 << 运算符,直接输出会打印字符对应的Unicode码点整数值,而非可见字符。

// 你的原有错误示例
#include <iostream>
using namespace std;

int main()
{
   char16_t value = u'猫';
   cout << " My Character " << value ;
   return 0;
}
Eclipse 2021 环境前置配置
  • 源文件编码设置:右键项目 → Properties → Resource → Text file encoding 选择 UTF-8
  • C标准配置:右键项目 → Properties → C/C++ Build → Settings → Tool Settings → GCC C++ Compiler → Dialect 选择 *ISO C20 (-std=c++20)*
  • 控制台编码配置:顶部菜单栏 Run → Run Configurations → 对应项目的运行配置 → Common → Encoding 选择 UTF-8
C++20 下正确实现代码

方案1:使用C++20 std::format 输出

该方法无需额外依赖,符合C++20标准规范:

#include <iostream>
#include <format>

int main()
{
    // char16_t 输出「猫」
    char16_t cat_u16 = u'猫';
    std::cout << "char16_t结果: " << std::format("{}", cat_u16) << '\n';

    // char32_t 输出「猫」
    char32_t cat_u32 = U'猫';
    std::cout << "char32_t结果: " << std::format("{}", cat_u32) << '\n';

    return 0;
}

方案2:转UTF-8多字节序列输出

如果编译器对std::format支持不完善,可以使用编码转换接口实现:

#include <iostream>
#include <cuchar>
#include <climits>

int main()
{
    char16_t cat_u16 = u'猫';
    char buf[MB_LEN_MAX] = {0};
    mbstate_t state{};
    c16rtomb(buf, cat_u16, &state);
    std::cout << "char16_t结果: " << buf << '\n';

    char32_t cat_u32 = U'猫';
    char buf2[MB_LEN_MAX] = {0};
    mbstate_t state2{};
    c32rtomb(buf2, cat_u32, &state2);
    std::cout << "char32_t结果: " << buf2 << '\n';

    return 0;
}

内容的提问来源于stack exchange,提问作者ahmed mokhtar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:15:01