MBCS与UNICODE字符集相互转换.

不同语言的操作系统默认的MBCS不一样, 有时需要与UNICODE相互转换.
代码如下:

#include <stdio.h>
#include <windows.h>
#include <iostream>
#include <string>

using namespace std;

wstring MultiCharToWideChar(string str)
{
    //获取大小,分配空间
    int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);
    wchar_t *buffer = new wchar_t[len+1];

    //转换
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);
    buffer[len]= L'\0';

    wstring return_value = buffer;
    delete [] buffer;

    return return_value;
}

string WideCharToMultiChar(wstring wstr)
{
    int len = 
        WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
    char *buffer = new char[len+1];

    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
    buffer[len] = '\0';

    string return_value = buffer;
    delete []buffer;

    return return_value;
}

#define CHARBUF "你好, 世界!";

void main()
{
    //设置为操作系统默认locale
    //否则cout无法输出中文
    setlocale(LC_ALL, "");

    char szBuf[] = CHARBUF;
    cout << szBuf << " length = " << strlen(szBuf) << endl;

    wstring wstr = MultiCharToWideChar(szBuf);
    wcout << wstr << " length = " << wstr.length() << endl;

    string str = WideCharToMultiChar(wstr);
    cout << str << " length = " << str.length() << endl;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章