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

如何在C++中将int类型转换为char16_t*?

实现int到char16_t*的转换函数

方法一:C++标准字符串流(跨平台推荐)

利用std::basic_ostringstream<char16_t>直接格式化数字到std::u16string,再动态分配内存生成char16_t*:

#include <sstream>
#include <cstdint>
#include <algorithm>

char16_t* intToChar16(int value) {
    std::basic_ostringstream<char16_t> oss;
    oss << value;
    std::u16string str = oss.str();

    // 分配包含空终止符的内存
    char16_t* result = new char16_t[str.size() + 1];
    // 复制字符串内容
    std::copy(str.begin(), str.end(), result);
    // 添加空终止符
    result[str.size()] = u'\0';

    return result;
}

关键注意:函数返回的是动态分配的内存,调用方使用后必须用delete[]释放,避免内存泄漏:

int myint = 3030;
char16_t* output = intToChar16(myint);
// 传入外部函数
external_function(output);
// 释放内存
delete[] output;

方法二:无手动内存管理的安全方案

如果外部函数仅需char16_t*参数(不要求内存所有权),可以返回std::u16string,通过data()获取指针,无需手动管理内存:

#include <sstream>
#include <cstdint>
#include <u16string>

std::u16string intToU16String(int value) {
    std::basic_ostringstream<char16_t> oss;
    oss << value;
    return oss.str();
}

使用示例:

int myint = 3030;
std::u16string str = intToU16String(myint);
// 只要str对象未销毁,str.data()就是有效的char16_t*
external_function(str.data());

方法三:C风格函数(Windows平台适配)

Windows系统中wchar_t为16位类型,与char16_t兼容,可通过C风格格式化函数实现:

#include <cstdint>
#include <cwchar>
#include <cstdio>

char16_t* intToChar16(int value) {
    // 缓冲区足够容纳int的最大长度(含负号和空字符)
    wchar_t temp_buf[12];
    swprintf_s(temp_buf, _countof(temp_buf), L"%d", value);

    size_t len = wcslen(temp_buf);
    char16_t* result = new char16_t[len + 1];
    // 复制并转换类型
    for (size_t i = 0; i <= len; ++i) {
        result[i] = static_cast<char16_t>(temp_buf[i]);
    }

    return result;
}

使用后同样需要用delete[]释放内存。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:45:06