sprintf:處理 ANSI/多字節字符串(char*)swprintf:處理 Unicode 寬字符串(wchar_t*)| 函數 | 格式符 | 對應參數類型 | 說明 |
|---|---|---|---|
sprintf | %s | char* | ANSI 字符串 |
%S | wchar_t* | Unicode → ANSI 轉換 | |
swprintf | %s | wchar_t* | Unicode 字符串 |
%S | char* | 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(szA, sizeof(szA), "%s", "ANSI Str");
_snwprintf(szW, _countof(szW), L"%s", L"Unicode Str");
比 *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);
MultiByteToWideChar/WideCharToMultiByteL"..." 寬字符串,"..." 窄字符串,_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,邊界轉換顯式處理。