USES_CONVERSION
宽窄字符的转换对于C++专业户来说是经常的动作。一般两种比较方便的方法:
1. C++:WideCharToMultiByte MultiByteToWideChar; C语言提供的转换函数为mbstowcs()/wcstombs()
2. C++:A2W W2A (USES_CONVERSION)
3. (追加)CStringA CStringW 之间仅用一个"="就完成了转换 神奇的很!!Love CString, Love Programming!
Method 1: #include <windows.h>
Method 2: #include <atlconv.h> 且使用A2W/W2A前一定要写USES_CONVERSION
Test Func:
void Func17() { //测试W2A时是否需要一倍的空间 cout<<"------------------------testing _W2A_------------------------"<<endl; CStringW cW = "nVIDIA"; int nLenW = cW.GetLength(); cout<<"W length: "<<nLenW<<endl; wcout<<L"W string: "<<cW.GetBuffer()<<endl; int nLenA = nLenW*2+1; char* szA = new char[nLenA]; memset(szA, 0, nLenA); cout<<"A length before translating: "<<nLenA<<endl; WideCharToMultiByte(CP_ACP, 0, cW.GetBuffer(), -1, szA, nLenA, NULL, NULL); //CP_ACP when to use other ? cout<<"A length after translated: "<<strlen(szA)<<endl; cout<<"A string: "<<szA<<endl; free(szA); szA = NULL; cout<<"--------------------------testing _A2W_----------------------------------"<<endl; CStringA cA = "Intel Chipset"; int nLenA2 = cA.GetLength(); cout<<"A length: "<<nLenA2<<endl; cout<<"A string: "<<cA.GetBuffer()<<endl; cout<<endl; int nLenW2 = nLenA2 + 1; // '\0' plus wchar_t* szW = new wchar_t[nLenW2]; memset(szW, 0, nLenW2); cout<<"W length b4 translating: "<<nLenW2<<endl; MultiByteToWideChar(CP_ACP, 0, cA.GetBuffer(), -1, szW, nLenW2); cout<<"W length a4 translated: "<<wcslen(szW)<<endl; wcout<<"W string: "<<szW<<endl; free(szW); szW = NULL; cout<<"----------------------testing USES_CONVERSION----------------"<<endl; CStringA cA3 = "Grok those URLs"; cout<<"cA3 b4: "<<cA3.GetBuffer()<<endl; USES_CONVERSION; CStringW cW3 = A2W(cA3.GetBuffer()); wcout<<cW3.GetBuffer()<<endl; cA3 = W2A(cW3.GetBuffer()); cout<<"cA3 a4: "<<cA3.GetBuffer()<<endl; //yeah~ }
但要注意:使用USES_CONVERSION是从堆栈上分配的内存,如果这么写:
void fn() { while(true) { { USES_CONVERSION; DoSomething(A2W("SomeString")); } } }
很可能导致stack overflow.
参考:http://www.cnblogs.com/carekee/articles/1935789.html
(追加)
cout<<"----------------------CStringA <--> CStringW can translated automatically----------------"<<endl; CStringW cW4= "Love CString, Love Programming"; CStringA cA4 = cW4; wcout<<"W string: "<<cW4.GetBuffer()<<endl; cout<<"A string: "<<cA4.GetBuffer()<<endl; cout<<endl<<endl; cW4 = cA4; wcout<<"W string : "<<cW4.GetBuffer()<<endl;

浙公网安备 33010602011771号