https://www.cnblogs.com/Hisin/archive/2012/05/01/2478092.html
在做MFC编程的时候,时常会碰到CString、CStringA、CStringW之间相互转换的问题,也即chat字符串与wchar_t字符串相互转换的问题。
现本人写了一个它们之间相互转换的函数,代码如下:
头文件CStringToolEx.h
#ifndef _CSTRING_TOOL_EX_
#define _CSTRING_TOOL_EX_
#include <cstringt.h>
//
// CString转CStringA
//
#ifndef CStrT2CStrA
#ifdef _UNICODE
#define CStrT2CStrA(cstr) CStrW2CStrA((cstr))
#else
#define CStrT2CStrA(cstr) (cstr)
#endif
#endif
//
// CString转CStringW
//
#ifndef CStrT2CStrW
#ifdef _UNICODE
#define CStrT2CStrW(cstr) (cstr)
#else
#define CStrT2CStrW(cstr) CStrA2CStrW((cstr))
#endif
#endif
//
// CStringA转CString
//
#ifndef CStrA2CStrT
#ifdef _UNICODE
#define CStrA2CStrT(cstr) CStrA2CStrW((cstr))
#else
#define CStrA2CStrT(cstr) (cstr)
#endif
#endif
//
// CStringW转CString
//
#ifndef CStrW2CStrT
#ifdef _UNICODE
#define CStrW2CStrT(cstr) (cstr)
#else
#define CStrW2CStrT(cstr) CStrW2CStrA((cstr))
#endif
#endif
//
// CStringA转CStringW
//
CStringW CStrA2CStrW(const CStringA &cstrSrcA);
//
// CStringW转CStringA
//
CStringA CStrW2CStrA(const CStringW &cstrSrcW);
#endif
源文件CStringToolEx.cpp
#include \"stdafx.h\"
#include \"CStringToolEx.h\"
#include <cstringt.h>
//
// CStringA转CStringW
//
CStringW CStrA2CStrW(const CStringA &cstrSrcA)
{
int len = MultiByteToWideChar(CP_ACP, 0, LPCSTR(cstrSrcA), -1, NULL, 0);
wchar_t *wstr = new wchar_t[len];
memset(wstr, 0, len*sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, LPCSTR(cstrSrcA), -1, wstr, len);
CStringW cstrDestW = wstr;
delete[] wstr;
return cstrDestW;
}
//
// CStringW转CStringA
//
CStringA CStrW2CStrA(const CStringW &cstrSrcW)
{
int len = WideCharToMultiByte(CP_ACP, 0, LPCWSTR(cstrSrcW), -1, NULL, 0, NULL, NULL);
char *str = new char[len];
memset(str, 0, len);
WideCharToMultiByte(CP_ACP, 0, LPCWSTR(cstrSrcW), -1, str, len, NULL, NULL);
CStringA cstrDestA = str;
delete[] str;
return cstrDestA;
}
继续阅读与本文标签相同的文章
上一篇 :
CNN超参数优化和可视化技巧详解
-
东京车展丰田玩把大的 人工智能自动驾驶都有 新RAV4也将混动亮相
2026-05-18栏目: 教程
-
“北斗+”为长沙公共安全“站岗”
2026-05-18栏目: 教程
-
滴滴与清华大学成立未来出行联合研究中心
2026-05-18栏目: 教程
-
三星S10被曝屏下指纹存在安全漏洞:任何人都还可以解锁
2026-05-18栏目: 教程
-
进博会“催生”上海首个保税展示展销场所
2026-05-18栏目: 教程
