首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

swprintf 與 sprintf 字符編碼轉換完全指南:ANSI 與 Unicode 互轉

     編輯:關於C語言

核心區別

  • sprintf:處理 ANSI/多字節字符串(char*)
  • swprintf:處理 Unicode 寬字符串(wchar_t*)

格式控制字符對應表

函數格式符對應參數類型說明
sprintf%schar*ANSI 字符串
%Swchar_t*Unicode → ANSI 轉換
swprintf%swchar_t*Unicode 字符串
%Schar*ANSI → Unicode 轉換

代碼示例

char szA[100];      // ANSI 緩衝區
WCHAR szW[100];     // Unicode 緩衝區

// 1. sprintf:全 ANSI
sprintf(szA, "%s", "ANSI Str");

// 2. sprintf:Unicode → ANSI
sprintf(szA, "%S", L"Unicode Str");

// 3. swprintf:全 Unicode
swprintf(szW, L"%s", L"Unicode Str");

// 4. swprintf:ANSI → Unicode
swprintf(szW, L"%S", "ANSI Str");

進階:_snprintf / _snwprintf 安全版本

// 防止緩衝區溢出
_snprintf(szA, sizeof(szA), "%s", "ANSI Str");
_snwprintf(szW, _countof(szW), L"%s", L"Unicode Str");

Windows API 字符串轉換函數(更推薦)

比 *printf 系列更健壯、支持代碼頁指定:

// ANSI → Unicode
int MultiByteToWideChar(UINT CodePage, DWORD dwFlags,
                        LPCSTR lpMultiByteStr, int cbMultiByte,
                        LPWSTR lpWideCharStr, int cchWideChar);

// Unicode → ANSI
int WideCharToMultiByte(UINT CodePage, DWORD dwFlags,
                        LPCWSTR lpWideCharStr, int cchWideChar,
                        LPSTR lpMultiByteStr, int cbMultiByte,
                        LPCSTR lpDefaultChar, LPBOOL lpUsedDefaultChar);

最佳實踐建議

  1. 內部統一用 Unicode:Windows 內核原生 Unicode,避免轉換開銷與數據丟失
  2. 邊界處理用 API:文件讀寫、網絡通訊、第三方庫接口處用 MultiByteToWideChar/WideCharToMultiByte
  3. 編譯設置:項目屬性 → Character Set → "Use Unicode Character Set"(VS 默認)
  4. 字面量前綴:L"..." 寬字符串,"..." 窄字符串,_T("...") 或 TEXT("...") 自動適配

常見錯誤

// 錯誤:格式符不匹配
swprintf(buf, L"%s", "ANSI");      // %s 期望 wchar_t*,傳入 char* → 未定義行為
sprintf(buf, "%s", L"Unicode");    // %s 期望 char*,傳入 wchar_t* → 未定義行為

// 正確:用大寫 S 觸發轉換
swprintf(buf, L"%S", "ANSI");      // ANSI → Unicode
sprintf(buf, "%S", L"Unicode");    // Unicode → ANSI

總結

sprintf/swprintf 的 %s/%S 機制提供了快速字符集轉換,但依賴當前代碼頁且無錯誤反饋。健壯代碼應優先使用 Windows 轉換 API,內部統一 Unicode,邊界轉換顯式處理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved