今天在unicode環境下寫程序,當將CString轉換成const char*類型是出現問題報錯:"cannot convert parameter 1 from 'wchar_t*' to 'const char*' "。搜索良久終於找到如下三種方法可以解決:
第一: 在COM環境下可使用如下方法,
CString strSQL;
strSQL.Format(_T('INSERT INTO Class(Name) VALUES('%s')'),
m_strName.GetBuffer(m_strName.GetLength()));
char* pchSQL =_com_util::ConvertBSTRToString(strSQL.GetBuffer(strSQL.GetLength()));
第二:使用操作系統給出的轉換函數,
int nSize = WideCharToMultiByte(CP_ACP,
NULL,
strSQL.GetBuffer(strSQL.GetLength()),
-1,
NULL,
0,
NULL,
FALSE);
char* pchStr = new char[nSize];
WideCharToMultiByte(CP_ACP,
NULL,
strSQL.GetBuffer(strSQL.GetLength()),
-1,
pchStr,
nSize,
NULL,
FALSE);
delete pchStr;
第三:使用C++庫給出的轉換函數:
#include<stdlib.h>
......
char pchSQL[128] = {0};
wcstombs(pchSQL, strSQL, strSQL.GetLength());