单字符宽字符互相转换
#include <stdlib.h>
size_t mbstowcs(wchar_t *pwcs, const char *s, size_t n); //转换单字符串为宽字符串
size_t wcstombs(char *mbstr, const wchar_t *wcstr, size_t count ); //转换宽字符串为单字符串
例如:
CString str = L"hello";
char sss[20];
wcstombs(sss,str.GetBuffer(),20); //转换宽字符为单字符
stl 宽字符到 单字符转换
wstring str = L"Hello";
std::wstring::size_type len = str.length();
std::string s(len*2,0);
size_t total = wcstombs(&s[0],str.c_str(),len*2);
s[total] = '/0';
return s;
mbtowc 和 wctomb 是单个字符相互转换
int len;
setlocale (LC_ALL, "chs"); //设置为简体中文环境
wchar_t wc = L'中';
wprintf(L"1个宽中文字符:%c /n",wc);
char* p = "中";
len = mbtowc (&wc, p, MB_LEN_MAX);
wprintf(L"单字符串转换为1个宽字符:%c 长度: %d/n",wc,len);
char pcmb[MB_LEN_MAX];
len = wctomb (pcmb, wc);
pcmb[len] = 0;
printf("宽字符转换为单字符串:%s 长度:%d/n",pcmb,len);
BYTE utf8[1024]; //utf8 字符串
wchar_t wstr[1024];
char mstr[1024];
//UTF-8 转换为宽字符
MultiByteToWideChar( CP_UTF8, 0, utf8,1024, wstr, sizeof(wstr)/sizeof(wstr[0]) );
WideCharToMultiByte( CP_ACP,0,wstr,-1,mstr,1024,NULL,NULL );
本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/zhuyooong/archive/2008/10/03/3013715.aspx
1.传给未分配内存的const char* (LPCTSTR)指针.
CString cstr(asdd);
const char* ch = (LPCTSTR)cstr;
ch指向的地址和cstr相同。但由于使用const保证ch不会修改,所以安全.
2.传给未分配内存的指针.
CString cstr = "ASDDSD";
char *ch = cstr.GetBuffer(cstr1.GetLength() + 1);
cstr.ReleaseBuffer();
//修改ch指向的值等于修改cstr里面的值.
//PS:用完ch后,不用delete ch,因为这样会破坏cstr内部空间,容易造成程序崩溃.
3.第二种用法。把CString 值赋给已分配内存的char *。
CString cstr1 = "ASDDSD";
int strLength = cstr1.GetLength() + 1;
char *pValue = new char[strLength];
strncpy(pValue, cstr1, strLength);
4.第三种用法.把CString 值赋给已分配内存char[]数组.
CString cstr2 = "ASDDSD";
int strLength1 = cstr1.GetLength() + 1;
char chArray[100];
memset(chArray,0, sizeof(bool) * 100); //将数组的垃圾内容清空.
#include <iostream>
#include <stdlib.h>
#include <string>
#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"
using namespace std;
using namespace System;
int main()
{
CString orig("Hello, World!");
wcout << orig << " (CString)" << endl;
// Convert to a char*
const size_t newsize = 100;
char nstring[newsize];
strcpy_s(nstring, orig);
strcat_s(nstring, " (char *)");
cout << nstring << endl;
// Convert to a wchar_t*
// You must first convert to a char * for this to work.
size_t origsize = strlen(orig) + 1;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);
wcscat_s(wcstring, L" (wchar_t *)");
wcout << wcstring << endl;
// Convert to a _bstr_t
_bstr_t bstrt(orig);
bstrt += " (_bstr_t)";
cout << bstrt << endl;
// Convert to a CComBSTR
CComBSTR ccombstr(orig);
if (ccombstr.Append(L" (CComBSTR)") == S_OK)
{
CW2A printstr(ccombstr);
cout << printstr << endl;
}
// Convert to a basic_string
string basicstring(orig);
basicstring += " (basic_string)";
cout << basicstring << endl;
// Convert to a System::String
String ^systemstring = gcnew String(orig);
systemstring += " (System::String)";
Console::WriteLine("{0}", systemstring);
delete systemstring;
}