char(utf8)转为wchar_t 中文乱码

MultiByteToWideChar函数可以将UTF-8编码的char类型字符串转换为wchar_t类型字符串。在将UTF-8编码的字符串转换为宽字符字符串时,可以指定CodePage参数为CP_UTF8,例如:

经过多次尝试,以下方法可行。

#include <stdio.h>  
#include <stdlib.h>  
#include <locale.h>  
#include <wchar.h>  
  
int main() {  
    setlocale(LC_ALL, "");  // 设置当前环境的字符编码为系统默认编码  
    char str[] = "Hello, 世界!";  // UTF-8编码的字符串  
    //size_t len = mbstowcs(NULL, str, 0);  // 计算目标缓冲区的大小  
    size_t len = sizeof(str);  // 计算目标缓冲区的大小  
    wchar_t wstr[len + 1];  // 定义目标宽字符缓冲区  
    int result = MultiByteToWideChar(CP_UTF8, 0, str, -1, wstr, len + 1);  // 转换宽字符序列  
    if (result == 0) {  
        printf("转换失败\n");  
    } else {  
        wprintf(L"%ls\n", wstr);  // 输出转换后的宽字符序列  
    }  
    return 0;  
}
WIN32 API 
FindFirstFile(tempFileFind, &FileData);

参数wchar_t类型,因此需要进行此类转换。

char *CCalibTools::wchar2char(const wchar_t *wstr)
{
    // 设置当前环境的字符编码为UTF-8
    setlocale(LC_ALL, "en_US.utf8");
    // 定义一个宽字符字符串
    // 将宽字符字符串转换为多字节字符串(使用UTF-8编码)
    int utf8_size = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
    char* utf8_str = new char[utf8_size];
    WideCharToMultiByte(CP_UTF8, 0, wstr, -1, utf8_str, utf8_size, NULL, NULL);
    // 输出转换后的多字节字符串(UTF-8编码)
    return utf8_str;
}

wchar_t *CCalibTools::char2wchar(const char *_str)
{
    //char to wchar_t start
    setlocale(LC_ALL, "");  // 设置当前环境的字符编码为系统默认编码
    int len_temp = strlen(_str);
    char str[len_temp + 1];
    memcpy(str,_str,len_temp);
    str[len_temp] = '\0';
    size_t len = sizeof(str);  // 计算目标缓冲区的大小
    wchar_t *tempFileFind = new wchar_t[len+1];
    int result = MultiByteToWideChar(CP_UTF8, 0, str, -1, tempFileFind, len + 1);  // 转换宽字符序列
    if (result == 0) {
        delete [] tempFileFind;
        return nullptr;
    } else {
        return tempFileFind;
    }
    //char to wchar_t end
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值