MFC/ATL 專案中常需將 CString 內容複製到 char* 緩衝區。直接傳遞 CString 給 strcpy_s/strcat_s 會導致編譯錯誤 C2664,因為 CString 內部為 Unicode (wchar_t) 而標準 C 函式要求 const char*。
CString strTime = t.Format(_T("db%Y%m%d*"));
char s[256];
strcpy_s(s, 256, GetExePath()); // 假設回傳 const char*
strcat_s(s, 256, strTime); // 錯誤:CString 無法隱式轉為 const char*
CW2A (ATL/MFC) 或 CT2A 轉換#include <atlconv.h> // 需包含
// 將 CString (Unicode) 轉為 ANSI char*
strcat_s(s, 256, CW2A(strTime)); // 或 CT2A(strTime)
// 完整範例
CString m = strTime;
strcpy_s(s, 256, GetExePath());
strcat_s(s, 256, CW2A(m)); // 正確
若專案設定為 Unicode(預設),更推薦使用寬字元安全函式,避免轉換損失:
wchar_t ws[256];
wcscpy_s(ws, 256, GetExePathW()); // 需提供寬字元版路徑
wcscat_s(ws, 256, strTime.GetString()); // CString::GetString() 回傳 const wchar_t*
CString 內部為 wchar_t* (Unicode)。strcpy_s/strcat_s 接受 char* (ANSI)。CW2A/CT2A 宏轉換(需 <atlconv.h>)。wcscpy_s/wcscat_s 配合 CString::GetString() 保持 Unicode 全程不轉碼。CString 與標準 C 字串函式的類型不匹配是 MFC 開發常見錯誤。掌握 CW2A/CT2A 轉換或改用寬字元版本,即可輕鬆解決編譯錯誤並避免編碼問題。