手机
当前位置:查字典教程网 >编程开发 >C语言 >深入理解c++中char*与wchar_t*与string以及wstring之间的相互转换
深入理解c++中char*与wchar_t*与string以及wstring之间的相互转换
摘要:复制代码代码如下:#ifndefUSE_H_#defineUSE_H_#include#include#includeusingnamesp...

复制代码 代码如下:

#ifndef USE_H_

#define USE_H_

#include <iostream>

#include <windows.h>

#include <string>

using namespace std;

class CUser

{

public:

CUser();

virtual~ CUser();

char* WcharToChar(const wchar_t* wp);

char* StringToChar(const string& s);

char* WstringToChar(const wstring& ws);

wchar_t* CharToWchar(const char* c);

wchar_t* WstringToWchar(const wstring& ws);

wchar_t* StringToWchar(const string& s);

wstring StringToWstring(const string& s);

string WstringToString(const wstring& ws);

void Release();

private:

char* m_char;

wchar_t* m_wchar;

};

#endif;

复制代码 代码如下:

#include "stdafx.h"

#include "use.h"

CUser::CUser()

:m_char(NULL)

,m_wchar(NULL)

{

}

CUser::~CUser()

{

Release();

}

char* CUser::WcharToChar(const wchar_t* wp)

{

Release();

int len= WideCharToMultiByte(CP_ACP,0,wp,wcslen(wp),NULL,0,NULL,NULL);

m_char=new char[len+1];

WideCharToMultiByte(CP_ACP,0,wp,wcslen(wp),m_char,len,NULL,NULL);

m_char[len]='';

return m_char;

}

wchar_t* CUser::CharToWchar(const char* c)

{

Release();

int len = MultiByteToWideChar(CP_ACP,0,c,strlen(c),NULL,0);

m_wchar=new wchar_t[len+1];

MultiByteToWideChar(CP_ACP,0,c,strlen(c),m_wchar,len);

m_wchar[len]='';

return m_wchar;

}

void CUser::Release()

{

if(m_char)

{

delete m_char;

m_char=NULL;

}

if(m_wchar)

{

delete m_wchar;

m_wchar=NULL;

}

}

char* CUser::StringToChar(const string& s)

{

return const_cast<char*>(s.c_str());

}

char* CUser::WstringToChar(const std::wstring &ws)

{

const wchar_t* wp=ws.c_str();

return WcharToChar(wp);

}

wchar_t* CUser::WstringToWchar(const std::wstring &ws)

{

return const_cast<wchar_t*>(ws.c_str());

}

wchar_t* CUser::StringToWchar(const string& s)

{

const char* p=s.c_str();

return CharToWchar(p);

}

string CUser::WstringToString(const std::wstring &ws)

{

string s;

char* p=WstringToChar(ws);

s.append(p);

return s;

}

wstring CUser::StringToWstring(const std::string &s)

{

wstring ws;

wchar_t* wp=StringToWchar(s);

ws.append(wp);

return ws;

}

如果涉及到CString,可以利用CString::GetBuffer()函数来进行转换,道理一样.

【深入理解c++中char*与wchar_t*与string以及wstring之间的相互转换】相关文章:

解析c中stdout与stderr容易忽视的一些细节

深入理解strcpy与memcpy的区别

分享C++面试中string类的一种正确写法

wchar_t,char,string,wstring之间的相互转换

c++中string类成员函数c_str()的用法

深入c++中临时对象的析构时机的详解

深入分析C中不安全的sprintf与strcpy

NSString与C字符串之间的相互转换

C++多字节字符与宽字节字符相互转换

C语言中字符串和数字的相互转换实现代码

精品推荐
分类导航