VC char和TCHAR之間轉換
阿新 • • 發佈:2018-12-22
char:計算機程式語言(c、c++、java、VFP等)中可容納單個字元的一種基本資料型別。
TCHAR:為了滿足Unicode編碼,對char的擴充套件,即_T(“str”)表示TCHAR型別
C++支援兩種字串,即常規的ANSI編碼(使用""包裹)和Unicode編碼(使用L""包裹),這樣對應的就有了兩套字串字串處理函式,比如:strlen和wcslen,分別用於處理兩種字串char和TCHAR型別
winnt.h標頭檔案中:
typedef WCHAR TCHAR, *PTCHAR;
表明 TCHAR 與 WCHAR 屬同一型別
char szA[100]; // ANSI
WCHAR szW[100]; // Unicode string buffer
// Normal sprintf:all strings are ANSI
sprintf(szA, "%s","ANSI Str");
// Converts Unicode string to ANSI
sprintf(szA,"%S",L"Unicode Str");
// Normal swprintf:all strings are Unicode
swprintf(szW,L"%s",L"Unicode Str");
// Converts ANSI string to Unicode
swprintf(szW,L"
注意:大寫S 和小寫s 的使用
===========================
應用例項:通過system函式程式呼叫啟動msc程式
void WSUS::OnBnClickedOk(){ CString strPath = NULL; // 申請路徑字串(TCHAR) char strChar[256]; // 申請路徑字串(char) m_CustomEdit.GetWindowTextW(strPath); // 獲取路徑儲存到strPath strPath.Replace(_T("\\"), _T("\\\\")); // 替換strPath中"\"為"\\",注意轉換符 //sprintf(strChar, "%s %S", "mmc.exe", strPath); // TCHAR轉換char型別 sprintf(strChar, "mmc.exe \"%S\"", strPath); // TCHAR轉換char型別 MessageBox(strPath, _T("title")); system(strChar); // 系統函式呼叫啟動msc程式 //WinExec((LPCSTR)_bstr_t(strPath), SW_SHOW); // 呼叫exe程式}
示例步驟:
1、獲取msc程式路徑strPath
2、替換strPath中"\"為"\\"字元
C:\Windows\System32\gpedit.msc
首先,通過 strPath.Replace(_T("\\"), _T("\\\\")); 轉換成:
C:\\Windows\\System32\\gpedit.msc
然後,通過 sprintf(strChar, "%s %S", "mmc.exe", strPath); 拼接字串為:
mmc.exe C:\\Windows\\System32\\gpedit.msc
3、system函式呼叫啟動msc程式
system(strChar);
4、啟動結果如下