CString转换成char*
CString strSource;//宣告CString
char* charSource; //宣告char*
法1:
charSource = (char*)strSource.GetBuffer(0);
法2:
charSource = (char*)strSource.GetBuffer(strSource.GetLength());
法3:
charSource = (char*)(LPCTSTR)strSource;
CString s = "abcd";
char *p = (LPSTR)(LPCTSTR)s;
from:
https://www.cnblogs.com/time-is-life/p/5757044.html
wchar* 转到 char*
//法一,使用_bstr_t转换。
#include <comdef.h> // you will need this
const WCHAR* wc = L"Hello World" ;
_bstr_t b(wc);
const char* c = b;
printf("Output: %s\n", c);
/方法二,使用conversion macros。 包含在头文件#include <atlconv.h>中,
使用需谨慎!因为转换字符串分配的空间在栈上,直到函数返回才释放。如归使用很多次,例如在递归函数里使用,容易造成内存溢出。/
#include <atlconv.h>
USES_CONVERSION;
WCHAR* wc = L"Hello World" ;
char* c = W2A(wc);
//方法三,使用sprintf,比较简洁。
char output[256];
WCHAR* wc = L"Hellow World";
sprintf(output, "%ws", wc );
char转 wchar
//方法一:使用mbstowcs函数。
const wchar_t *GetWC(const char *c)
{
const size_t cSize = strlen(c)+1;
wchar_t* wc = new wchar_t[cSize];
mbstowcs (wc, c, cSize);
return wc;
}
//方法二:使用USES_CONVERSION。 用法及注意事项同上。
USES_CONVERSION;
char* c = L"Hello World" ;
Wchar* wc = A2W(c);
//方法三:使用swprintf函数,推荐使用。
wchar_t ws[100];
swprintf(ws, 100, L"%hs", "ansi string");
https://blog.csdn.net/jeanphorn/article/details/45745739
什么是?
char*和string字符串中的字符都是一个字符占一个字节的;
wchar_t* 宽字符,大部分字符都以一个字符占固定长度的字节 (2字节) 储存;
【注】:一个中文通常占用2个字节,当需要处理中文时,可以首先将string转换成char*,然后将char转换成wchar_t即可。
怎么做?
在window环境中,可以利用
MultiByteToWideChar();
WideCharToMultiByte();
两个API函数来实现转换,方法如下:
(1)单字节字符串string转双字节字符串wchar_t*
#include <windows.h>
#include <string>
//不要忘记在使用完wchar_t*后delete[]释放内存
wchar_t *multi_Byte_To_Wide_Char(const string& pKey)
{
//string 转 char*
char* pCStrKey = pKey.c_str();
//第一次调用返回转换后的字符串长度,用于确认为wchar_t*开辟多大的内存空间
int pSize = MultiByteToWideChar(CP_OEMCP, 0, pCStrKey, strlen(pCStrKey) + 1, NULL, 0);
wchar_t *pWCStrKey = new wchar_t[pSize];
//第二次调用将单字节字符串转换成双字节字符串
MultiByteToWideChar(CP_OEMCP, 0, pCStrKey, strlen(pCStrKey) + 1, pWCStrKey, pSize);
return pWCStrKey;
}
(2)双字节字符串wchar_t转换成单字节字符串char或string
#include <windows.h>
#include <string>
//不要忘记使用完char*后delete[]释放内存
char* wide_Char_To_Multi_Byte(wchar_t* pWCStrKey)
{
//第一次调用确认转换后单字节字符串的长度,用于开辟空间
int pSize = WideCharToMultiByte(CP_OEMCP, 0, pWCStrKey, wcslen(pWCStrKey), NULL, 0, NULL, NULL);
char* pCStrKey = new char[pSize+1];
//第二次调用将双字节字符串转换成单字节字符串
WideCharToMultiByte(CP_OEMCP, 0, pWCStrKey, wcslen(pWCStrKey), pCStrKey, pSize, NULL, NULL);
pCStrKey[pSize] = '\0';
return pCStrKey;
//如果想要转换成string,直接赋值即可
//string pKey = pCStrKey;