先看如何将CString转char*:
包涵头文件
#include <iostream>
#include <stdio.h>
#include <afx.h>
工程属性设置为:
封装函数:
函数功能:将多字节字符转为单字符型
参数1:[in][out] pDest 指向目标地址指针,即转换后存放的地址
参数2:[in] pSource 引用原CString对象
int My_WcharToChar(char* pDest,CString& pSource)
{
wchar_t* pawstr = NULL;
pawstr = pSource.GetBuffer(pSource.GetLength()+1);
wcstombs(pDest,pawstr,pSource.GetLength()+1);
return TRUE;
}
完整测试代码:
#include <iostream>
#include <stdio.h>
#include <afx.h>
using namespace std;
int My_WcharToChar(char* pDest,CString& pSource);
int main()
{
CString str = _T("WINDOWS7");
char pChar[200];
My_WcharToChar(pChar,str);
cout <<"pChar = "<<pChar<<endl;
return TRUE;
}
int My_WcharToChar(char* pDest,CString& pSource)
{
wchar_t* pawstr = NULL;
pawstr = pSource.GetBuffer(pSource.GetLength()+1);
wcstombs(pDest,pawstr,pSource.GetLength()+1);
return TRUE;
}
输出结果:
如何将char*转为CString:
char name[100] = "厉害了罗大爷";
CString strName;
strName = CA2CT(name); // 这样就可以了
char name[] 是窄字符的字符串,
CString 有两种可能,如果有UNICODE宏就是宽字符CStringW,如果没有这个宏就是窄字符CStringA。
用CA2CT可以正确处理上面两种情况的
补充:微软基础类库(英语:Microsoft Foundation Classes,简称MFC)是一个微软公司提供的类库(class libraries),以C++类的形式封装了Windows API,并且包含一个应用程序框架,以减少应用程序开发人员的工作量。其中包含的类包含大量Windows句柄封装类和很多Windows的内建控件和组件的封装类。
先看如何将CString转char*:
包涵头文件
#include <iostream> #include <stdio.h> #include <afx.h>
工程属性设置为:
封装函数:
函数功能:将多字节字符转为单字符型
参数1:[in][out] pDest 指向目标地址指针,即转换后存放的地址
参数2:[in] pSource 引用原CString对象
int My_WcharToChar(char* pDest,CString& pSource) { wchar_t* pawstr = NULL; pawstr = pSource.GetBuffer(pSource.GetLength()+1); wcstombs(pDest,pawstr,pSource.GetLength()+1); return TRUE; }
完整测试代码:
#include <iostream> #include <stdio.h> #include <afx.h> using namespace std; int My_WcharToChar(char* pDest,CString& pSource);
int main() {
CString str = _T("WINDOWS7"); char pChar[200]; My_WcharToChar(pChar,str); cout <<"pChar = "<<pChar<<endl;
return TRUE; }
int My_WcharToChar(char* pDest,CString& pSource) { wchar_t* pawstr = NULL; pawstr = pSource.GetBuffer(pSource.GetLength()+1); wcstombs(pDest,pawstr,pSource.GetLength()+1); return TRUE; }
输出结果:

char name[100] = "厉害了罗大爷";
CString strName;
strName = CA2CT(name); // 这样就可以了
char name[] 是窄字符的字符串,
CString 有两种可能,如果有UNICODE宏就是宽字符CStringW,如果没有这个宏就是窄字符CStringA。
用CA2CT可以正确处理上面两种情况的
补充:微软基础类库(英语:Microsoft Foundation Classes,简称MFC)是一个微软公司提供的类库(class libraries),以C++类的形式封装了Windows API,并且包含一个应用程序框架,以减少应用程序开发人员的工作量。其中包含的类包含大量Windows句柄封装类和很多Windows的内建控件和组件的封装类。