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;
}


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