[DEMO]宽字节与多字节的相互转换

仅适用Windows平台

// main.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

//C 头文件,扩展名为.c或.cpp时用
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>

//C++头文件,只能扩展名为.cpp时用
//#include <iostream>
//#include <string>
//#include <locale>

int main()
{
    setlocale(LC_ALL, "");

    const char* csz = "中国cn";

    size_t len = 0;
    errno_t err = 0;

    wchar_t* wsz = NULL;
    mbstowcs_s(&len, NULL, 0, csz, 0);   //len是字符数,包括末尾0
    //len = strlen(csz) * sizeof(char) + 1;
    wsz = (wchar_t*)malloc(len * sizeof(wchar_t));
    err = mbstowcs_s(NULL, wsz, len, csz, _TRUNCATE);    //_TRUNCATE,空间不足时截断,末尾置0
    //一般不会出错 err = 0
    if(!err)
        printf("%ws\n", wsz);

    char* sz = NULL;
    wcstombs_s(&len, NULL, 0, wsz, 0);   //len是字符数,包括末尾0
    //len = wcslen(wsz) * sizeof(wchar_t) + 1;
    sz = (char*)malloc(len * sizeof(char));
    err = wcstombs_s(NULL, sz, len, wsz, _TRUNCATE);    //_TRUNCATE,空间不足时截断,末尾置0
    //一般不会出错 err = 0
    if (!err)
        printf("%s\n", sz);

    free(wsz);
    free(sz);
}




posted @ 2019-05-10 14:52  鞋带儿  阅读(160)  评论(0编辑  收藏  举报