直接上代码,看代码就知道怎么转换了:
////////////////////////////////////
//
// CString 和 各种字符串格式互转
// huidong 2021.1.2
//
// CString 需要的头
#include <atlstr.h>
// printf,wprintf头
#include <stdio.h>
// string,wstring头
#include <string>
using namespace std;
// setlocale头
#include <locale>
// wstring和string转换函数需要用的头
#include <comutil.h>
#pragma comment(lib, "comsuppw.lib")
string wtos(const wstring& ws)
{
_bstr_t t = ws.c_str();
char* pchar = (char*)t;
string result = pchar;
return result;
}
wstring stow(const string& s)
{
_bstr_t t = s.c_str();
wchar_t* pwchar = (wchar_t*)t;
wstring result = pwchar;
return result;
}
int main()
{
// 为了使转换时中文没问题
setlocale(LC_ALL, "chs");
// 以下代码运行环境为:
// 编译器:VS2019
// 项目:unicode字符集
CString cstr = "abcd 哈哈~ ABCD";
// CString->wstring
wstring wstr = cstr.AllocSysString();
wprintf(wstr.c_str());
printf(" 1\n");
// CString->wchar_t
wchar_t wchar[20] = { 0 };
wsprintf(wchar,(LPCTSTR)cstr);
wprintf(wchar);
printf(" 2\n");
// CString->string
string str = wtos((LPCTSTR)cstr);
printf(str.c_str());
printf(" 3\n");
// CString->char
char ch[20] = { 0 };
sprintf_s(ch,20, wtos((LPCTSTR)cstr).c_str());
printf(ch);
printf(" 4\n");
// wchar->CString
cstr.Format(L"%ls", wchar);
wprintf(cstr.AllocSysString());
printf(" 5\n");
// char->CString
cstr = ch;
wprintf(cstr.AllocSysString());
printf(" 6\n");
// wstring->CString
cstr.Format(L"%ls", wstr.c_str());
wprintf(cstr.AllocSysString());
printf(" 7\n");
// string->CString
cstr = str.c_str();
wprintf(cstr.AllocSysString());
printf(" 8\n");
return 0;
}
如果程序运行结果显示了8行“abcd 哈哈~ ABCD”,则表示此程序的所有转换都成功了,如下图:
CString 在某些方面比string一类好很多。