char与wchar_t相互转换

1、wchar类型初始化

wchar_t* wc = L"这是 wchar 测试";

2、wchar_t* 转 char*

char * wchar2char(const wchar_t* wchar )
{
    char * m_char;    
    int len= WideCharToMultiByte( CP_ACP ,0,wchar ,wcslen( wchar ), NULL,0, NULL ,NULL );    
    m_char= new char[len+1];     
    WideCharToMultiByte( CP_ACP ,0,wchar ,wcslen( wchar ),m_char,len, NULL ,NULL );     
    m_char[len]= '\0';     
    return m_char; 
}

3、char* 转 wchar_t*

wchar_t * char2wchar(const char* cchar) 
{     
    wchar_t *m_wchar;    
    int len = MultiByteToWideChar( CP_ACP ,0,cchar ,strlen( cchar), NULL,0);     
    m_wchar= new wchar_t[len+1];     
    MultiByteToWideChar( CP_ACP ,0,cchar,strlen( cchar),m_wchar,len);     
    m_wchar[len]= '\0' ;    
    return m_wchar; 
} 

测试代码:

#include 
#include 
#include 

using namespace std;

char * wchar2char(const wchar_t* wchar )
{
    char * m_char;    
    int len= WideCharToMultiByte( CP_ACP ,0,wchar ,wcslen( wchar ), NULL,0, NULL ,NULL );    
    m_char= new char[len+1];     
    WideCharToMultiByte( CP_ACP ,0,wchar ,wcslen( wchar ),m_char,len, NULL ,NULL );     
    m_char[len]= '\0';     
    return m_char; 
}

wchar_t * char2wchar(const char* cchar) 
{     
    wchar_t *m_wchar;    
    int len = MultiByteToWideChar( CP_ACP ,0,cchar ,strlen( cchar), NULL,0);     
    m_wchar= new wchar_t[len+1];     
    MultiByteToWideChar( CP_ACP ,0,cchar,strlen( cchar),m_wchar,len);     
    m_wchar[len]= '\0' ;    
    return m_wchar; 
} 


int main()
{
    wchar_t* wc = L"这是 wchar 测试";
    char* c = wchar2char(wc);
    wchar_t* wc2 = char2wchar(c);
    char* c2 = wchar2char(wc2);

    cout << "c: " << c << endl;
    cout << "c2: " << c2 << endl;
    getchar();
    return 0;
}

你可能感兴趣的:(C++)